{"id":3164,"date":"2023-01-05T18:19:21","date_gmt":"2023-01-05T23:19:21","guid":{"rendered":"https:\/\/dft.wiki\/?p=3164"},"modified":"2026-04-02T08:59:37","modified_gmt":"2026-04-02T12:59:37","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 and human friendly script language that among the most popular ones.<\/p>\n<p>Its potential is virtually unlimited when considered the vast amount of libraries freely available in packed 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>\u00a0CREATING QR CODES<\/strong><\/p>\n<p>Install the dependency called <code>segno<\/code>:<\/p>\n<pre>pip install segno<\/pre>\n<p>Now, the library (<code>segno<\/code>) can be imported and used 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 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 the RGBA 8-digit notation, the first 6-digts represents the RGB (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>) plus 2-digits for the transparency (from 00 to FF, where 00 means no transparency and FF means full transparency). See more colorful notations at 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>Image with transparency.<\/li>\n<\/ul>\n<\/li>\n<li>SVG\n<ul>\n<li>Vetorized image with transprency.<\/li>\n<\/ul>\n<\/li>\n<li>TXT\n<ul>\n<li>No color or transparency supported.<\/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 the output to a stream\/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 will respond 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) -&gt; 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 using 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>On the terminal, the API 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 rembg-app.py 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 call 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 generates the same result with a simplified 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 module <code>rembg<\/code> can be called 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 &gt; output.png<\/code> for piping a remote file. If started as an HTTP server (<code>rembg s<\/code>) and be called via <code>curl \"http:\/\/localhost:5000\/?url=https:\/\/example.com\/input.png\" &gt; output.png<\/code><\/p>\n<p>While some objects are not properly recognised, 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 will send the request directly to the &#8220;clear&#8221; Internet, while the following will send via Tor:<\/p>\n<pre>curl -x socks5h:\/\/127.0.0.1:9050 'https:\/\/api.ipify.org?format=txt'<\/pre>\n<p>The key fact is the utilisation of a SOCKS5 Proxy. The same concept will be used in Python with the module <code>requests<\/code>.<\/p>\n<p>Stem [<a href=\"https:\/\/stem.torproject.org\/\">Link<\/a>] is the Python module capable of interacting with Tor&#8217;s ControlPort to gather metrics about the connection:<\/p>\n<pre>pip install stem<\/pre>\n<p>Edit the configuration of Tor:<\/p>\n<pre>sudo nano \/etc\/tor\/torrc<\/pre>\n<p>Uncomment the following line to enable the ControlPort where you can get :<\/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>Manually start tor in one terminal and leave it there running.<\/p>\n<pre>tor<\/pre>\n<p>In another terminal, execute the created script. The expected output might reveal what Tor exit node&#8217;s IP was used to reach the &#8220;clear&#8221; Internet plus the total amount of bytes send 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 dependent module:<\/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>You might encounter the following pop-up windows. They might look a bit different depending on the operating system or graphic 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\" \/>\u00a0 \u00a0\u00a0<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 executing an application it is very common to pass arguments in a certain order and use them by the index of each argument&#8217;s order.<\/p>\n<p>The library <code>argparse<\/code> takes care of received arguments in any order, checking for type, assigning default values, and helping the user with a help menu.<\/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 executeble 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>More available options<\/p>\n<ul>\n<li><strong>required=True<\/strong>\n<ul>\n<li>make an argument mandatory.<\/li>\n<\/ul>\n<\/li>\n<li><strong>default=0<\/strong>\n<ul>\n<li>sets a default values if not provided.<\/li>\n<\/ul>\n<\/li>\n<li><strong>nargs=&#8217;*&#8217;<\/strong>\n<ul>\n<li>allows any number or arguments.<\/li>\n<\/ul>\n<\/li>\n<li><strong>choices=[&#8216;local&#8217;, &#8216;remote&#8217;]<\/strong>\n<ul>\n<li>limits the possible values.<\/li>\n<\/ul>\n<\/li>\n<li><strong>action=&#8217;store_true&#8217;<\/strong>\n<ul>\n<li>makes an argument a boolean flag set to false if not set.<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<hr \/>\n<p><strong>PRETTY PRINT<\/strong><\/p>\n<p>The <code>pprint<\/code> module provides a &#8220;pretty-print&#8221; of data structures like objects, arrays, and dictionaries.<\/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> instantly make your loops show a smart progress meter. Just 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.comm\", 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>Yes, there are ways you can compile the Python scripting language into machine code. See project Nuitka [<a href=\"https:\/\/nuitka.net\/\">Link<\/a>], which can produce a binary file that contains no readable string to accomplish the following objectives:<\/p>\n<ul>\n<li>Intellectual property protection,<\/li>\n<li>Increased performance,<\/li>\n<li>Optionally, use the Standalone \/ 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 combined are invaluable 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 compilation requires the system to have Python runtime and all the dependencies available, while the Standalone produces a whole directory <code>.dist<\/code> that needs to be copied to the destination host to execute.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python is a versatile and human friendly script language that among the most popular ones. [&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":16,"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/posts\/3164\/revisions"}],"predecessor-version":[{"id":5415,"href":"https:\/\/dft.wiki\/index.php?rest_route=\/wp\/v2\/posts\/3164\/revisions\/5415"}],"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}]}}