{"id":3164,"date":"2023-01-05T18:19:21","date_gmt":"2023-01-05T23:19:21","guid":{"rendered":"https:\/\/dft.wiki\/?p=3164"},"modified":"2026-06-08T17:20:23","modified_gmt":"2026-06-08T21:20:23","slug":"cool-python-tricks","status":"publish","type":"post","link":"https:\/\/dft.wiki\/?p=3164","title":{"rendered":"Python Tips and Tricks"},"content":{"rendered":"<p>Python is a versatile, human-friendly scripting language and one of the most popular ones available today.<\/p>\n<p>Its potential is virtually unlimited given the vast number of libraries freely available through package managers such as PIP.<\/p>\n<p>Index of tricks in this post:<\/p>\n<ol>\n<li>Creating QR Codes<\/li>\n<li>Removing Background from Images<\/li>\n<li>HTTP Connections via Tor (Darkweb)<\/li>\n<li>Easy Graphic User Interface (GUI)<\/li>\n<\/ol>\n<hr \/>\n<p><strong>CREATING QR CODES<\/strong><\/p>\n<p>Install the <code>segno<\/code> dependency:<\/p>\n<pre>pip install segno<\/pre>\n<p>Once installed, import and use the library in your code:<\/p>\n<pre>import segno\r\n\r\nqrcode = segno.make(\"Text to be encoded\")\r\nqrcode.save(\"fileName.png\", dark=\"darkblue\", light=\"white\", border=5, scale=10)\r\nqrcode.save(\"fileName.png\", dark=\"darkblue\", light=None, scale=10)\r\nqrcode.terminal()<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3166\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName.png\" alt=\"\" width=\"350\" height=\"350\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName.png 350w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-300x300.png 300w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-150x150.png 150w\" sizes=\"auto, (max-width: 350px) 100vw, 350px\" \/><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3168\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-2.png\" alt=\"\" width=\"330\" height=\"330\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-2.png 330w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-2-300x300.png 300w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-2-150x150.png 150w\" sizes=\"auto, (max-width: 330px) 100vw, 330px\" \/><\/p>\n<p>For RGB with Alpha Transparency using 8-digit notation:<\/p>\n<pre>qrcode.save(\"fileName.png\", dark=\"ff000080\", scale=10)<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3167\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-1.png\" alt=\"\" width=\"330\" height=\"330\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-1.png 330w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-1-300x300.png 300w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/fileName-1-150x150.png 150w\" sizes=\"auto, (max-width: 330px) 100vw, 330px\" \/><\/p>\n<p><strong>Note:<\/strong> In RGBA 8-digit notation, the first 6 digits represent the RGB value (from <span style=\"color: #000;\">000000<\/span> to <span style=\"color: #f00;\">FF<\/span><span style=\"color: #0f0;\">FF<\/span><span style=\"color: #00f;\">FF<\/span>), and the last 2 digits represent transparency (from 00 to FF, where 00 is fully opaque and FF is fully transparent). See more color notations in the Segno documentation [<a href=\"https:\/\/segno.readthedocs.io\/en\/1.4.1\/colorful-qrcodes.html\">Link<\/a>].<\/p>\n<p>List of popular output formats (serializers):<\/p>\n<ul>\n<li>PNG\n<ul>\n<li>Supports transparency.<\/li>\n<\/ul>\n<\/li>\n<li>SVG\n<ul>\n<li>Vectorized image with transparency.<\/li>\n<\/ul>\n<\/li>\n<li>TXT\n<ul>\n<li>No color or transparency support.<\/li>\n<\/ul>\n<\/li>\n<li>PDF\n<ul>\n<li>Transparency not supported.<\/li>\n<\/ul>\n<\/li>\n<li>Streams\/Buffers\n<ul>\n<li>Capable of streaming output to a stream or buffer.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>Outputting to a buffer (read more at [<a href=\"https:\/\/segno.readthedocs.io\/en\/stable\/api.html#segno.QRCode.save\">Link<\/a>]):<\/p>\n<pre>import segno\r\nimport io\r\nqrcode = segno.make(\"Text to be encoded\")\r\nbuffer = io.BytesIO()\r\nqrcode.save(buffer, kind='png')\r\nprint(buffer.getvalue())<\/pre>\n<p>API Endpoint \/ HTTP Server that responds with a QR Code:<\/p>\n<pre>#!\/usr\/bin\/env python3\r\nfrom http.server import SimpleHTTPRequestHandler\r\nfrom socketserver import TCPServer\r\nfrom urllib.parse import unquote\r\nimport segno\r\nimport io\r\n\r\ndef http_server(host_port):\r\n  class CustomHandler(SimpleHTTPRequestHandler):\r\n    def do_GET(self) -> None:\r\n\r\n      def send_200(content_type=\"application\/json\"):\r\n        self.send_response(200)\r\n        self.send_header(\"Content-type\", content_type)\r\n        self.send_header(\"Cache-Control\", 'no-cache, no-store, must-revalidate')\r\n        self.send_header(\"Pragma\", 'no-cache')\r\n        self.send_header(\"Expires\", '0')\r\n        self.end_headers()\r\n\r\n      self.path = unquote(self.path)\r\n\r\n      if self.path == '\/' or self.path == '\/qrcode.png':\r\n        if self.path == '\/':\r\n          send_200('text\/html')\r\n          self.wfile.write(bytes('<img decoding=\"async\" class=\"center\" src=\"\/qrcode.png\" alt=\"Paris\" \/>', 'utf-8'))\r\n        elif self.path == '\/qrcode.png':\r\n          send_200('image\/jpeg')\r\n          qrcode = segno.make(\"Text to be encoded\") \r\n          buffer = io.BytesIO() \r\n          qrcode.save(buffer, kind='png', scale=10)\r\n          self.wfile.write(bytes(buffer.getvalue()))\r\n        else:\r\n          return\r\n        return\r\n\r\n      else:\r\n        self.send_response(404)\r\n        self.end_headers()\r\n        return\r\n\r\n\r\n  class _TCPServer(TCPServer):\r\n    allow_reuse_address = True\r\n  httpd = _TCPServer(host_port, CustomHandler)\r\n  httpd.serve_forever()\r\n\r\ntry:\r\n  http_server(('0.0.0.0',8080))\r\nexcept KeyboardInterrupt:\r\n  print(' Interrupted')\r\n  exit()\r\n<\/pre>\n<p>Navigate to the following address in your browser:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3170\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-16-53-44.png\" alt=\"\" width=\"532\" height=\"468\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-16-53-44.png 532w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-16-53-44-300x264.png 300w\" sizes=\"auto, (max-width: 532px) 100vw, 532px\" \/><\/p>\n<p>The terminal will log both requests:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3171\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-16-52-27.png\" alt=\"\" width=\"705\" height=\"87\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-16-52-27.png 705w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-16-52-27-300x37.png 300w\" sizes=\"auto, (max-width: 705px) 100vw, 705px\" \/><\/p>\n<hr \/>\n<p><strong>REMOVING BACKGROUND FROM IMAGES<\/strong><\/p>\n<pre>pip install rembg<\/pre>\n<p>OR (for GPU support)<\/p>\n<pre>pip install rembg[gpu]<\/pre>\n<p>Create the file <code>rembg-app.py<\/code> with the following content:<\/p>\n<pre>#!\/usr\/bin\/python3\r\nfrom rembg import remove\r\nimport sys\r\n\r\ninput_path = sys.argv[1]\r\noutput_path = sys.argv[2]\r\n\r\nwith open(input_path, 'rb') as i:\r\n    with open(output_path, 'wb') as o:\r\n        input = i.read()\r\n        output = remove(input)\r\n        o.write(output)<\/pre>\n<p>Make the script executable and run it as follows:<\/p>\n<pre>chmod +x rembg-app.py\r\n.\/rembg-app.py input.png output.png<\/pre>\n<p>Alternatively, the following code produces the same result with simpler logic:<\/p>\n<pre>from rembg import remove\r\nfrom PIL import Image\r\n\r\ninput_path = 'input.png'\r\noutput_path = 'output.png'\r\n\r\ninput = Image.open(input_path)\r\noutput = remove(input)\r\noutput.save(output_path)<\/pre>\n<p><strong>Note:<\/strong> The <code>rembg<\/code> module can also be used directly from the command line: <code>rembg i input.png output.png<\/code> for a local file, <code>rembg p input_dir output_dir<\/code> for a local directory, or <code>curl -s http:\/\/example.com\/input.png | rembg i > output.png<\/code> to pipe a remote file. It can also be started as an HTTP server with <code>rembg s<\/code> and called via <code>curl \"http:\/\/localhost:5000\/?url=https:\/\/example.com\/input.png\" > output.png<\/code>.<\/p>\n<p>While some objects are not recognised perfectly, most are impressively extracted:<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3176\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05.png\" alt=\"\" width=\"2183\" height=\"839\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05.png 2183w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05-300x115.png 300w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05-1024x394.png 1024w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05-768x295.png 768w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05-1536x590.png 1536w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-21-05-2048x787.png 2048w\" sizes=\"auto, (max-width: 2183px) 100vw, 2183px\" \/><\/p>\n<hr \/>\n<p><strong>HTTP REQUEST VIA TOR NETWORK (DARKWEB)<\/strong><\/p>\n<pre>curl 'https:\/\/api.ipify.org?format=txt'<\/pre>\n<p>The command above sends the request directly over the regular Internet, while the following routes it through Tor:<\/p>\n<pre>curl -x socks5h:\/\/127.0.0.1:9050 'https:\/\/api.ipify.org?format=txt'<\/pre>\n<p>The key is the use of a SOCKS5 proxy. The same approach is used in Python with the <code>requests<\/code> module.<\/p>\n<p>Stem [<a href=\"https:\/\/stem.torproject.org\/\">Link<\/a>] is a Python module that interacts with Tor&#8217;s ControlPort to gather connection metrics:<\/p>\n<pre>pip install stem<\/pre>\n<p>Edit the Tor configuration file:<\/p>\n<pre>sudo nano \/etc\/tor\/torrc<\/pre>\n<p>Uncomment the following line to enable the ControlPort:<\/p>\n<pre>ControlPort 9051<\/pre>\n<p>Create a script with the following content:<\/p>\n<pre>#!\/usr\/bin\/python3\r\nimport requests, time\r\nfrom stem import Signal\r\nfrom stem.control import Controller\r\n\r\n# Set the headers for the request\r\nheaders = {'User-Agent': 'Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/70.0.3538.102 Safari\/537.36'}\r\nPROXIES = {\r\n    'http': 'socks5:\/\/127.0.0.1:9050',\r\n    'https': 'socks5:\/\/127.0.0.1:9050'\r\n}\r\n\r\n# Initialize the controller for the Tor network\r\nwith Controller.from_port(address='127.0.0.1', port=9051) as controller:\r\n    controller.authenticate()\r\n\r\n    url = 'https:\/\/api.ipify.org?format=txt'\r\n\r\n    print('Public IP used for the request:')\r\n    while True:\r\n    # Set the new IP address\r\n        controller.signal(Signal.NEWNYM)\r\n        response = requests.get(url, headers=headers, proxies=PROXIES)\r\n        print('IP:', str(response.content, 'utf-8'), '-', controller.get_info(\"traffic\/read\"), 'bytes received -', controller.get_info(\"traffic\/written\"), 'bytes sent.')\r\n        time.sleep(10)<\/pre>\n<p>Start Tor in one terminal and leave it running:<\/p>\n<pre>tor<\/pre>\n<p>In a second terminal, run the script. The output will show the Tor exit node&#8217;s IP used to reach the regular Internet, along with the total bytes sent and received.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3185\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-20-44-42.png\" alt=\"\" width=\"689\" height=\"316\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-20-44-42.png 689w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-20-44-42-300x138.png 300w\" sizes=\"auto, (max-width: 689px) 100vw, 689px\" \/><\/p>\n<hr \/>\n<p><strong>EASY GRAPHIC USER INTERFACE<\/strong><\/p>\n<p>Install the required modules:<\/p>\n<pre>sudo apt-get install python3-tk -y\r\npip install easygui<\/pre>\n<p>Create a script with the following content:<\/p>\n<pre>#!\/usr\/bin\/python3\r\nimport easygui\r\n\r\nread_file_path = easygui.fileopenbox(title='Select file')\r\nwrite_file_path = easygui.filesavebox(title='Save file to...')\r\nprompt_question = easygui.ynbox('Continue?', 'Titlebox', ('Yes', 'No'))\r\nmessage_box = easygui.msgbox('This is a basic message box.', 'Title Goes Here')\r\nselected_option = easygui.buttonbox('Survey', 'Question', ('Answer 1', 'Answer 2', 'Answer 3'))<\/pre>\n<p>The following pop-up windows may appear. Their appearance may vary depending on your operating system or desktop environment.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3180\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-44-28.png\" alt=\"\" width=\"436\" height=\"311\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-44-28.png 436w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-44-28-300x214.png 300w\" sizes=\"auto, (max-width: 436px) 100vw, 436px\" \/>    <img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3179\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-44-47.png\" alt=\"\" width=\"436\" height=\"311\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-44-47.png 436w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-44-47-300x214.png 300w\" sizes=\"auto, (max-width: 436px) 100vw, 436px\" \/><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3183\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-42-27.png\" alt=\"\" width=\"696\" height=\"255\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-42-27.png 696w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-42-27-300x110.png 300w\" sizes=\"auto, (max-width: 696px) 100vw, 696px\" \/><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3182\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-42-34.png\" alt=\"\" width=\"696\" height=\"255\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-42-34.png 696w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-42-34-300x110.png 300w\" sizes=\"auto, (max-width: 696px) 100vw, 696px\" \/><\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-3181\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-43-31.png\" alt=\"\" width=\"696\" height=\"255\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-43-31.png 696w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2023-01-05-18-43-31-300x110.png 300w\" sizes=\"auto, (max-width: 696px) 100vw, 696px\" \/><\/p>\n<hr \/>\n<p><strong>ARGUMENT PARSING<\/strong><\/p>\n<p>When running a script, it is common to pass arguments in a specific order and access them by index. The <code>argparse<\/code> library handles arguments in any order, validates types, assigns default values, and generates a help menu automatically.<\/p>\n<ul>\n<li>Optional<\/li>\n<\/ul>\n<pre>#!\/usr\/bin\/python3\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--exec', type=str, help=\"local executable file\")\r\nparser.add_argument('--addr', type=str, help=\"remote host's address\")\r\nparser.add_argument('--port', type=int, help=\"remote host's port\")\r\nargs = parser.parse_args()\r\n\r\nif args.exec != None:\r\n    print('Execute:', args.exec)\r\nelif args.addr != None and args.port != None:\r\n    print('Connect to:', args.host, 'on port:', args.port)\r\nelse:\r\n    print('Please provide an executable or a remote host + port.')<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-4229\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-20-10.png\" alt=\"\" width=\"512\" height=\"185\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-20-10.png 512w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-20-10-300x108.png 300w\" sizes=\"auto, (max-width: 512px) 100vw, 512px\" \/><\/p>\n<ul>\n<li>Positional<\/li>\n<\/ul>\n<pre>#!\/usr\/bin\/python3\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('addr', type=str, help=\"remote host's address\")\r\nparser.add_argument('port', type=int, help=\"remote host's port\")\r\nargs = parser.parse_args()\r\n\r\nprint('Connect to:', args.host, 'on port:', args.port)<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-4230\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-23-56.png\" alt=\"\" width=\"539\" height=\"218\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-23-56.png 539w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-23-56-300x121.png 300w\" sizes=\"auto, (max-width: 539px) 100vw, 539px\" \/><\/p>\n<ul>\n<li>Multiple Arguments<\/li>\n<\/ul>\n<pre>#!\/usr\/bin\/python3\r\nimport argparse\r\n\r\nparser = argparse.ArgumentParser(description=\"This script connects to a remote host\")\r\nparser.add_argument('-r', type=str, nargs=2, help=\"remote host's address followed by the port\")\r\nargs = parser.parse_args()\r\n\r\nif args.r is not None:\r\n    print('Connect to:', args.r[0], 'on port:', args.r[1])<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-4231\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-40-40.png\" alt=\"\" width=\"460\" height=\"201\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-40-40.png 460w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-from-2024-05-01-17-40-40-300x131.png 300w\" sizes=\"auto, (max-width: 460px) 100vw, 460px\" \/><\/p>\n<p>Additional available options:<\/p>\n<ul>\n<li><strong>required=True<\/strong>\n<ul>\n<li>Makes an argument mandatory.<\/li>\n<\/ul>\n<\/li>\n<li><strong>default=0<\/strong>\n<ul>\n<li>Sets a default value if the argument is not provided.<\/li>\n<\/ul>\n<\/li>\n<li><strong>nargs=&#8217;*&#8217;<\/strong>\n<ul>\n<li>Allows any number of arguments.<\/li>\n<\/ul>\n<\/li>\n<li><strong>choices=[&#8216;local&#8217;, &#8216;remote&#8217;]<\/strong>\n<ul>\n<li>Limits the accepted values.<\/li>\n<\/ul>\n<\/li>\n<li><strong>action=&#8217;store_true&#8217;<\/strong>\n<ul>\n<li>Treats the argument as a boolean flag, defaulting to false if not provided.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<hr \/>\n<p><strong>PRETTY PRINT<\/strong><\/p>\n<p>The <code>pprint<\/code> module formats data structures such as objects, arrays, and dictionaries for easier reading.<\/p>\n<pre>from pprint import *\r\nobject = {\"object\":'chair',\"quantity\":2,\"colors\": [\"red\", \"white\", \"blue\"]}\r\npprint(object, depth=1, width=10)<\/pre>\n<hr \/>\n<p><strong>PROGRESS BAR<\/strong><\/p>\n<p><code>tqdm<\/code> adds a smart progress meter to any loop. Simply wrap any iterable with <code>tqdm(iterable)<\/code>.<\/p>\n<pre>from tqdm import tqdm\r\nimport time\r\nfor i in tqdm(range(10000), desc=\"Processing\"):\r\n    time.sleep(0.0001)<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-4803\" src=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-From-2025-04-15-22-38-01.png\" alt=\"\" width=\"655\" height=\"87\" srcset=\"https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-From-2025-04-15-22-38-01.png 655w, https:\/\/dft.wiki\/wp-content\/uploads\/sites\/15\/2023\/01\/Screenshot-From-2025-04-15-22-38-01-300x40.png 300w\" sizes=\"auto, (max-width: 655px) 100vw, 655px\" \/><\/p>\n<hr \/>\n<p><strong>SENDING EMAILS VIA SMTP<\/strong><\/p>\n<pre>#!\/usr\/bin\/python3\r\nimport smtplib\r\nfrom email.mime.text import MIMEText\r\n\r\ndef send_email(server, port, email, password, recipient, subject, body):\r\n  try:\r\n    message = MIMEText(body)\r\n    message[\"From\"] = email\r\n    message[\"To\"] = recipient\r\n    message[\"Subject\"] = subject\r\n    with smtplib.SMTP(server, port) as smtp_server:\r\n      smtp_server.sendmail(email, recipient, message.as_string())\r\n    print(\"Email sent successfully!\")\r\n  except Exception as e:\r\n    print(f\"Could not send email using server {server} and port {port}. Error: {e}\")\r\n\r\nsend_email(server=\"smtp.example.com\", port=25, email=\"user@example.com\", password=\"\", recipient=\"user@example.com\", subject=\"Test Email\", body=\"This is a test email.\")<\/pre>\n<hr \/>\n<p><strong>COMPILING CODE<\/strong><\/p>\n<p>Python can be compiled into machine code using Nuitka [<a href=\"https:\/\/nuitka.net\/\">Link<\/a>], which produces a binary with no readable strings. This enables:<\/p>\n<ul>\n<li>Intellectual property protection<\/li>\n<li>Increased performance<\/li>\n<li>Optionally, Standalone or OneFile mode to:\n<ul>\n<li>Bundle the Python runtime inside the executable<\/li>\n<li>Embed all dependencies and libraries<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p>These features are particularly useful for building lean microservices with CI\/CD pipelines.<\/p>\n<p>Installation:<\/p>\n<pre>sudo apt install patchelf python3-pip python3-venv -y\r\npython3 -m venv .venv\r\nsource .venv\/bin\/activate\r\npython3 -m pip install -U \"Nuitka[all]\"<\/pre>\n<p>Building:<\/p>\n<pre>python3 -m nuitka app.py<\/pre>\n<p>OR<\/p>\n<pre>python3 -m nuitka --mode=standalone app.py<\/pre>\n<p>OR<\/p>\n<pre>python3 -m nuitka --mode=onefile --follow-imports app.py<\/pre>\n<p>The standard build requires Python and all dependencies to be installed on the target system, while Standalone produces a <code>.dist<\/code> directory that can be copied and run on any compatible host.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python is a versatile, human-friendly scripting language and one of the most popular ones available [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[5],"tags":[],"class_list":["post-3164","post","type-post","status-publish","format-standard","hentry","category-programming"],"_links":{"self":[{"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/posts\/3164","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dft.wiki\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3164"}],"version-history":[{"count":17,"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/posts\/3164\/revisions"}],"predecessor-version":[{"id":5662,"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/posts\/3164\/revisions\/5662"}],"wp:attachment":[{"href":"https:\/\/dft.wiki\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3164"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dft.wiki\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3164"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dft.wiki\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3164"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}