{"id":696,"date":"2019-09-11T12:18:59","date_gmt":"2019-09-11T12:18:59","guid":{"rendered":"https:\/\/www.askpython.com\/?p=696"},"modified":"2019-12-16T05:01:39","modified_gmt":"2019-12-16T05:01:39","slug":"python-command-line-arguments","status":"publish","type":"post","link":"https:\/\/www.askpython.com\/python\/python-command-line-arguments","title":{"rendered":"Python Command Line Arguments &#8211; 3 Ways to Read\/Parse"},"content":{"rendered":"\n<p>Python command-line arguments are the parameters provided to the script while executing it. The command-line arguments are used to provide specific inputs to the program. <\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">What is the benefit of Python Command Line Arguments?<\/h2>\n\n\n\n<p>Python command-line arguments help us to keep our program generic in nature. For example, we can write a program to process a CSV file. If we pass the CSV file name from the command-line, then our program will work for any CSV file. This will make our program loosely coupled and it will be easy to maintain it.<\/p>\n\n\n\n<p>Another benefit of command-line arguments is the additional security that comes with it. Let&#8217;s say we have a program to save data into the database. If we store the database credentials in the script or some configuration file, it can be accessed and executed by anyone having access to the files. But, if the user\/password is provided as a command-line argument, then it&#8217;s not present in the file system and our program is more secured.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How to Pass Command-line Arguments in Python?<\/h2>\n\n\n\n<p>If you are running the python script from the terminal, just pass the arguments after the script name. The arguments are separated with white space characters.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n$ python script.py arg1 arg2 ... argN\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Passing Command-line arguments in PyCharm<\/h2>\n\n\n\n<p>PyCharm is the most popular IDE for Python programming. If you want to pass command-line arguments to a python program, go to &#8220;Run &gt; Edit Configurations&#8221; and set the Parameters value and save it.<\/p>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"788\" src=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/09\/python-command-line-arguments-PyCharm-1024x788.png\" alt=\"Python Command Line Arguments PyCharm\" class=\"wp-image-697\" srcset=\"https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/09\/python-command-line-arguments-PyCharm-1024x788.png 1024w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/09\/python-command-line-arguments-PyCharm-300x231.png 300w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/09\/python-command-line-arguments-PyCharm-768x591.png 768w, https:\/\/www.askpython.com\/wp-content\/uploads\/2019\/09\/python-command-line-arguments-PyCharm.png 1200w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><figcaption>Python Command Line Arguments PyCharm<\/figcaption><\/figure><\/div>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">How to Read Command-line arguments in Python Script?<\/h2>\n\n\n\n<p>There are three popular modules to read and parse command-line arguments in the Python script.<\/p>\n\n\n\n<ol class=\"wp-block-list\"><li>sys.argv<\/li><li>getopt<\/li><li>argparse<\/li><\/ol>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">1. Reading Python Command-line arguments using the sys module<\/h2>\n\n\n\n<p>The command-line arguments are stored in the sys module <code>argv<\/code> variable, which is a <a href=\"https:\/\/www.askpython.com\/python\/list\/python-list\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"list (opens in a new tab)\">list<\/a> of strings. We can read the command-line arguments from this list and use it in our program.<\/p>\n\n\n\n<p>Note that the script name is also part of the command-line arguments in the <code>sys.argv<\/code> variable.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport sys\n\nif len(sys.argv) != 2:\n    raise ValueError(&#039;Please provide email-id to send the email.&#039;)\n\nprint(f&#039;Script Name is {sys.argv&#x5B;0]}&#039;)\n\nemail = sys.argv&#x5B;1]\n\nprint(f&#039;Sending test email to {email}&#039;)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n$ python3.7 command-line-args.py test@askpython.com\nScript Name is command-line-args.py\nSending test email to test@askpython.com\n$ python3.7 command-line-args.py                   \nTraceback (most recent call last):\n  File &quot;command-line-args.py&quot;, line 4, in &lt;module&gt;\n    raise ValueError(&#039;Please provide email-id to send the email.&#039;)\nValueError: Please provide email-id to send the email.\n$\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">2. Parsing Command-line arguments using the getopt module<\/h2>\n\n\n\n<p>Python getopt module works in a similar way as the Unix getopt() function. This module is helpful when you want the script to accept options and their values, similar to the many Unix commands.<\/p>\n\n\n\n<p>This module works in conjunction with the sys.argv to parse the command-line arguments and extract the options values in a list of <a href=\"https:\/\/www.askpython.com\/python\/tuple\/python-tuple\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"tuples (opens in a new tab)\">tuples<\/a>.<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport getopt\nimport sys\n\nargv = sys.argv&#x5B;1:]\n\nopts, args = getopt.getopt(argv, &#039;x:y:&#039;)\n\n# list of options tuple (opt, value)\nprint(f&#039;Options Tuple is {opts}&#039;)\n\n# list of remaining command-line arguments\nprint(f&#039;Additional Command-line arguments list is {args}&#039;)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n$ python3.7 command-line-args.py -x 1 -y 2 A B            \nOptions Tuple is &#x5B;(&#039;-x&#039;, &#039;1&#039;), (&#039;-y&#039;, &#039;2&#039;)]\nAdditional Command-line arguments list is &#x5B;&#039;A&#039;, &#039;B&#039;]\n$ \n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">3. Parsing Command-line arguments using argparse module<\/h2>\n\n\n\n<p>We can use Python argparse module also to parse command-line arguments. There are a lot of options with argparse module.<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>positional arguments<\/li><li>the help message<\/li><li>the default value for arguments<\/li><li>specifying the data type of argument and many more.<\/li><\/ul>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\nimport argparse\n\n# create parser\nparser = argparse.ArgumentParser()\n\n# add arguments to the parser\nparser.add_argument(&quot;language&quot;)\nparser.add_argument(&quot;name&quot;)\n\n# parse the arguments\nargs = parser.parse_args()\n\n# get the arguments value\nif args.language == &#039;Python&#039;:\n\tprint(&quot;I love Python too&quot;)\nelse:\n\tprint(&quot;Learn Python, you will like it&quot;)\n\t\nprint(f&#039;Hello {args.name}, this was a simple introduction to argparse module&#039;)\n<\/pre><\/div>\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code \"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n$ python3.7 command-line-args.py Python David\nI love Python too\nHello David, this was a simple introduction to argparse module\n$\n$ python3.7 command-line-args.py Java Lisa   \nLearn Python, you will like it\nHello Lisa, this was a simple introduction to argparse module\n$\n$ python3.7 command-line-args.py -h       \nusage: command-line-args.py &#x5B;-h] language name\n\npositional arguments:\n  language\n  name\n\noptional arguments:\n  -h, --help  show this help message and exit\n$\n<\/pre><\/div>\n\n\n<p>Notice that the help message is automatically generated by the argparse module. <\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">Conclusion<\/h2>\n\n\n\n<p>If your script requires simple command-line arguments, you can go with sys.argv. But, if your program accepts a lot of positional arguments, default argument values, help messages, etc, then you should use argparse module. The getopt module works too but it&#8217;s confusing and hard to understand.<\/p>\n\n\n\n<hr class=\"wp-block-separator\"\/>\n\n\n\n<h2 class=\"wp-block-heading\">References:<\/h2>\n\n\n\n<ul class=\"wp-block-list\"><li><a rel=\"noreferrer noopener\" aria-label=\"sys.argv (opens in a new tab)\" href=\"https:\/\/docs.python.org\/3.7\/library\/sys.html#sys.argv\" target=\"_blank\">sys.argv<\/a><\/li><li><a rel=\"noreferrer noopener\" aria-label=\"getopt module (opens in a new tab)\" href=\"https:\/\/docs.python.org\/3.7\/library\/getopt.html?highlight=getopt#getopt.getopt\" target=\"_blank\">getopt module<\/a><\/li><li><a href=\"https:\/\/docs.python.org\/3.7\/library\/argparse.html\" target=\"_blank\" rel=\"noreferrer noopener\" aria-label=\"argparse module (opens in a new tab)\">argparse module<\/a><\/li><\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Python command-line arguments are the parameters provided to the script while executing it. The command-line arguments are used to provide specific inputs to the program. What is the benefit of Python Command Line Arguments? Python command-line arguments help us to keep our program generic in nature. For example, we can write a program to process [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-696","post","type-post","status-publish","format-standard","hentry","category-python"],"blocksy_meta":[],"_links":{"self":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/696","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/comments?post=696"}],"version-history":[{"count":0,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/posts\/696\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/media?parent=696"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/categories?post=696"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.askpython.com\/wp-json\/wp\/v2\/tags?post=696"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}