{"id":3616,"date":"2021-06-28T06:49:40","date_gmt":"2021-06-28T06:49:40","guid":{"rendered":"https:\/\/cloudxlab.com\/blog\/?p=3616"},"modified":"2021-06-28T07:02:56","modified_gmt":"2021-06-28T07:02:56","slug":"how-to-handle-command-line-arguments-in-python","status":"publish","type":"post","link":"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/","title":{"rendered":"How to handle Command Line Arguments in Python?"},"content":{"rendered":"\n<p>When you are running python programs from the command line, you can pass various arguments to the program and your program can handle it.<\/p>\n\n\n\n<p>Here is a quick snippet of code that I will be explaining later:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">import sys\nif __name__ == \"__main__\":\n    print(\"You passed: \", sys.argv)<\/code><\/pre>\n\n\n\n<p>When you run this program from the command line, you will get this kind of results:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$ python cmdargs.py\n You passed:  ['cmdargs.py']<\/pre>\n\n\n\n<p>Notice that the <code>sys.argv<\/code> is an array of strings containing all arguments passed to the program. And the first value(at zeroth index) of this array is the name of the program itself. You can put all kinds of check on it.<\/p>\n\n\n\n<!--more-->\n\n\n\n<pre class=\"wp-block-preformatted\">$ python cmdargs.py 1 2 \"CloudxLab Inc\"\n You passed:  ['cmdargs.py', '1', '2', 'CloudxLab Inc']<\/pre>\n\n\n\n<h2>Why name check?<\/h2>\n\n\n\n<p>Please note that we are checking if the <code>__name__<\/code> is equal to <code>__main__<\/code> in order to avoid this code being executed when this file is included as a module.<\/p>\n\n\n\n<p>The following code also runs fine.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">import sys\nprint(\"You passed: \", sys.argv)<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">$ python cmdargs.py\n You passed:  ['cmdargs.py']<\/pre>\n\n\n\n<p>In python, you can include one python program in another program by using import.  This is where the problem occurs.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$ python\n Python 3.9.5 (default, May  4 2021, 03:36:27)\n [Clang 12.0.0 (clang-1200.0.32.29)] on darwin\n Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n<strong>import cmdargs<\/strong>\n<strong>You passed:  ['']<\/strong>         <\/pre>\n\n\n\n<p>Notice that the moment we imported <code>cmdargs<\/code>, it ran our print statement. To avoid this code being executed during import, we put a check if the <code>__name__<\/code> is equal to <code>__main__<\/code>.<\/p>\n\n\n\n<h2>What about return value?<\/h2>\n\n\n\n<p>In Unix, every program returns a value to the operating system. In python, this is usually done by passing a signal in <code>exit()<\/code> like this:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">import sys\nif __name__ == \"__main__\":\n    print(\"You passed: \", sys.argv)\n    exit(146)<\/code><\/pre>\n\n\n\n<p>You can check this by using `$?` special variable in shell.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$ python cmdargs.py 1 2\n You passed:  ['cmdargs.py', '1', '2']\n (venv) MacBook-Air:codefun sandeep$ echo $?\n <strong>146<\/strong><\/pre>\n\n\n\n<p>Notice that 146 being print by <code>echo $?<\/code> As a matter of convention, in case of success, our program should return 0 and in case of failure, it should return a non-zero value.<\/p>\n\n\n\n<h2>Parsing the command line<\/h2>\n\n\n\n<p>There is a very interesting module in Python which helps in parsing command line arguments called <code>argparse<\/code><\/p>\n\n\n\n<p>You can utilize it to make your application handle really complex arguments. Here is a small snippet of code from a file <code>create_screen_shots.py<\/code> where I used <code>argparse<\/code> recently to do complex processing of arguments.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code class=\"\">import argparse\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser(description='Export notes from google slides. The files will be created per slide. The name will n.txt where n starts from 0.')\n    parser.add_argument('slidesid', metavar='SlideId', type=str, help='The id of the Google Slide.')\n    parser.add_argument('dir', metavar='Directory', type=str, help='The directory in which these screenshots will be saved.', nargs='?')\n    parser.add_argument('total_slides', metavar='total_slides', type=int, help='Total Number of slides', nargs='?')\n  \n    args = parser.parse_args()\n    # Do something with it\n    print(args.slidesid, args.dir, args.total_slides )\n<\/code><\/pre>\n\n\n\n<p>As added bonus, it also provides a nice help manual to the user of my program.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">$ python create_screen_shots.py --help\n usage: create_screen_shots.py [-h] SlideId [Directory] [total_slides]\n Export notes from google slides. The files will be created per slide. The name will n.txt where n starts from 0.\n positional arguments:\n   SlideId       The id of the Google Slide.\n   Directory     The directory in which these screenshots will be saved.\n   total_slides  Total Number of slides\n optional arguments:\n   -h, --help    show this help message and exit<\/pre>\n\n\n\n<p>You can find out more about it in <a href=\"https:\/\/docs.python.org\/3\/library\/argparse.html\">Python Doc of argparse.<\/a> <\/p>\n\n\n\n<p>Happy Learning!<\/p>\n\n\n\n<p>You can experiment with and learn command-line arguments and various technologies using <a href=\"https:\/\/cloudxlab.com\/lab\/\">CloudxLab<\/a> without installing anything on your computer.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>When you are running python programs from the command line, you can pass various arguments to the program and your program can handle it. Here is a quick snippet of code that I will be explaining later: When you run this program from the command line, you will get this kind of results: $ python &hellip; <a href=\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;How to handle Command Line Arguments in Python?&#8221;<\/span><\/a><\/p>\n","protected":false},"author":14,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[1],"tags":[134,132,133,94],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v16.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to handle Command Line Arguments in Python? | CloudxLab Blog<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to handle Command Line Arguments in Python? | CloudxLab Blog\" \/>\n<meta property=\"og:description\" content=\"When you are running python programs from the command line, you can pass various arguments to the program and your program can handle it. Here is a quick snippet of code that I will be explaining later: When you run this program from the command line, you will get this kind of results: $ python &hellip; Continue reading &quot;How to handle Command Line Arguments in Python?&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"CloudxLab Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/cloudxlab\" \/>\n<meta property=\"article:published_time\" content=\"2021-06-28T06:49:40+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2021-06-28T07:02:56+00:00\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@CloudxLab\" \/>\n<meta name=\"twitter:site\" content=\"@CloudxLab\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\">\n\t<meta name=\"twitter:data1\" content=\"3 minutes\">\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebSite\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#website\",\"url\":\"https:\/\/cloudxlab.com\/blog\/\",\"name\":\"CloudxLab Blog\",\"description\":\"Learn AI, Machine Learning, Deep Learning, Devops &amp; Big Data\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":\"https:\/\/cloudxlab.com\/blog\/?s={search_term_string}\",\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/#webpage\",\"url\":\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/\",\"name\":\"How to handle Command Line Arguments in Python? | CloudxLab Blog\",\"isPartOf\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/#website\"},\"datePublished\":\"2021-06-28T06:49:40+00:00\",\"dateModified\":\"2021-06-28T07:02:56+00:00\",\"author\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/#\/schema\/person\/4835f1b3d5000626cb15e9311d748e09\"},\"breadcrumb\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"item\":{\"@type\":\"WebPage\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/\",\"url\":\"https:\/\/cloudxlab.com\/blog\/\",\"name\":\"Home\"}},{\"@type\":\"ListItem\",\"position\":2,\"item\":{\"@id\":\"https:\/\/cloudxlab.com\/blog\/how-to-handle-command-line-arguments-in-python\/#webpage\"}}]},{\"@type\":\"Person\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#\/schema\/person\/4835f1b3d5000626cb15e9311d748e09\",\"name\":\"Sandeep Giri\",\"image\":{\"@type\":\"ImageObject\",\"@id\":\"https:\/\/cloudxlab.com\/blog\/#personlogo\",\"inLanguage\":\"en-US\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/1393214840cf7455bb4cba055cb30468?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/1393214840cf7455bb4cba055cb30468?s=96&d=mm&r=g\",\"caption\":\"Sandeep Giri\"},\"sameAs\":[\"https:\/\/cloudxlab.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","_links":{"self":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/3616"}],"collection":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/users\/14"}],"replies":[{"embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/comments?post=3616"}],"version-history":[{"count":5,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/3616\/revisions"}],"predecessor-version":[{"id":3621,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/posts\/3616\/revisions\/3621"}],"wp:attachment":[{"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/media?parent=3616"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/categories?post=3616"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/cloudxlab.com\/blog\/wp-json\/wp\/v2\/tags?post=3616"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}