{"id":127188,"date":"2022-08-11T11:17:24","date_gmt":"2022-08-11T11:17:24","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=565520"},"modified":"2022-08-11T11:17:24","modified_gmt":"2022-08-11T11:17:24","slug":"a-simple-guide-for-using-command-line-arguments-in-python","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/08\/11\/a-simple-guide-for-using-command-line-arguments-in-python\/","title":{"rendered":"A Simple Guide for Using Command Line Arguments in Python"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;565520&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;2&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (2 votes)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (2 votes) <\/div>\n<\/div>\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube\"><a href=\"https:\/\/blog.finxter.com\/a-simple-guide-for-using-command-line-arguments-in-python\/\"><img decoding=\"async\" src=\"https:\/\/blog.finxter.com\/wp-content\/plugins\/wp-youtube-lyte\/lyteCache.php?origThumbUrl=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzuwTBBK1Q6U%2Fhqdefault.jpg\" alt=\"YouTube Video\"><\/a><figcaption><\/figcaption><\/figure>\n<p>In this lesson, we will learn several methods for using arguments in the command line and how we can manipulate them to run in our pre-written Python scripts.<\/p>\n<p>The three methods we will explore and compare are:<\/p>\n<ul>\n<li><code>sys.argv<\/code><\/li>\n<li><code>argparse<\/code><\/li>\n<li><code>getopt<\/code><\/li>\n<\/ul>\n<p>These are ordered for ease of use and simplicity.\u00a0 <\/p>\n<p>I\u2019ve added the<strong><em> <\/em><\/strong><code>getopt()<\/code> method for demonstration purposes and have included it at the end because I find it the least useful of the three &#8211; you may have a different opinion, so check it out and make your own conclusions.<\/p>\n<h2>Method 1- sys.argv<\/h2>\n<p>First, we will need to import the <code><a href=\"https:\/\/blog.finxter.com\/how-to-execute-system-commands-with-python\/\" data-type=\"post\" data-id=\"32971\" target=\"_blank\" rel=\"noreferrer noopener\">sys<\/a><\/code> module &#8211; <em>\u201cSystem- specific parameters and functions.\u201d<\/em><\/p>\n<p><code>argv<\/code> stands for <strong><em>\u201cargument vector\u201d<\/em><\/strong>, and is basically a variable that contains arguments passed through the command line.<\/p>\n<p>I\u2019m using the VScode text editor for my scripts, as you can see in the file path, and then follow that by calling \u201cPython\u201d before the actual file name and arguments.\u00a0 This will be the same with each method.\u00a0 <\/p>\n<p>You can abbreviate <strong><em>Python<\/em><\/strong> as <strong><em>py<\/em><\/strong> after vscode if you wish to save on typing and that will work fine.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import sys print('What is the name of the script?', sys.argv[0])\nprint('How many arguments?', len(sys.argv))\nprint('What are the arguments?', str(sys.argv))\n<\/pre>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\n# Adding arguments on command line\n(base) PS C:\\Users\\tberr\\.vscode> python test_command.py 3 4 5 6\n<\/pre>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">What is the name of the Script? test_command.py\nHow many arguments? 5\nWhat are the arguments? ['test_command.py', '3', '4', '5', '6']\n<\/pre>\n<p>We can see that the file name is the first argument located at the <code>[0]<\/code> index position and the four integers are located at <code>index[1:]<\/code> (1, 2, 3, 4) in our <a href=\"https:\/\/blog.finxter.com\/python-lists\/\" data-type=\"post\" data-id=\"7332\" target=\"_blank\" rel=\"noreferrer noopener\">list<\/a> of strings.<\/p>\n<p>Now let\u2019s do some code that is a little more involved.<\/p>\n<p>Simple script for adding numbers with the numbers entered on the command line.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import sys # total arguments\nn = len(sys.argv)\nprint(\"Total arguments passed:\", n) # Arguments passed\nprint(\"\\nName of Python script:\", sys.argv[0]) print(\"\\nArguments passed:\", end = \" \")\nfor i in range(1, n): print(sys.argv[i], end = \" \") # Addition of numbers\nSum = 0\n# Using argparse module (we will talk about argparse next)\nfor i in range(1, n): Sum += int(sys.argv[i]) print(\"\\n\\nResult:\", Sum)<\/pre>\n<p>Output with arguments entered on command line:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">(base) PS C:\\Users\\tberr\\.vscode> python test_command.py 4 5 7 8\nTotal arguments passed: 5 Name of Python script: test_command.py Arguments passed: 4 5 7 8 Result: 24<\/pre>\n<p>This gives the user the total arguments passed, the name of the script, arguments passed (not including script name), and the \u201cSum\u201d of the integers.&nbsp; Now let\u2019s get to the<strong><em> argparse <\/em><\/strong>method.<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Note<\/strong>: If you are getting an \u2018error\u2019 or different results than expected when you pass arguments on the command line, make sure that the file you\u2019re calling has been <strong>saved. <\/strong>If your Python file has been changed or is new it will not work until you do so.<\/p>\n<h2>Method 2 &#8211; argparse<\/h2>\n<p>Parser for command-line options, arguments, and sub-commands.<\/p>\n<p><code>argparse<\/code> is recommended over <code>getopt<\/code> because it is simpler and uses fewer lines of code.<\/p>\n<p>Code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import argparse # Initialize the parser\nparser = argparse.ArgumentParser(description = 'process some integers.') # Adding Arguments\nparser.add_arguments('integers', metavar = 'N', type = int, nargs = '+', help = 'an integer for the accumulator') parser.add_arguments(dest = 'accumulate', action = 'store_const\", const = sum, help = 'sum the integers') args = parser.parse_args()\nprint(args.accumulate(args.integers))<\/pre>\n<p>We see that first, we initialize the parser and then add arguments with the \u2018<code>parser.add_arguments<\/code>\u2019 section of the code.\u00a0 <\/p>\n<p>We also add some help messages to guide the user on what is going on with the script.\u00a0 This will be very clear when we enter arguments on the command line and see our output.<\/p>\n<p>Output:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"powershell\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># Add arguments on the command line. -h (for help) and four integers (base) PS C:\\Users\\tberr\\.vscode> python argparse.py -h 5 3 6 7\nusage: argparse.py [-h] N [N ...] Process some integers. positional arguments: N an integer for the accumulator accumulate sum the integers optional arguments: -h, &#8211; help show this help message and exit # Run code again without the help argument, just sum the integers.\n(base) PS C:\\Users\\tberr\\.vscode> python argParse.py 5 3 6 7\n21<\/pre>\n<\/p>\n<p>This is an excellent, clean way to pass arguments on the command line, and the addition of the \u2018<code>help<\/code>\u2019 argument can make this very clear for the user.<\/p>\n<p>For more details on arguments like [\u2018<code>metavar<\/code>\u2019], [\u2018<code>const<\/code>\u2019], [\u2018<code>action<\/code>\u2019], and [\u2018<code>dest<\/code>\u2019], check out this <a href=\"https:\/\/stackoverflow.com\/questions\/19124304\/what-does-metavar-and-action-mean-in-argparse-in-python\" target=\"_blank\" rel=\"noreferrer noopener\">LINK<\/a><\/p>\n<h2>Method 3 &#8211; getopt<\/h2>\n<p>A method for parsing command line options and parameters, very similar to the <code>getopt()<\/code> function in the <a href=\"https:\/\/blog.finxter.com\/c-developer-income-and-opportunity-2\/\" data-type=\"post\" data-id=\"204465\" target=\"_blank\" rel=\"noreferrer noopener\">C language<\/a>.\u00a0 This is some basic code to get the name of the user on the command line.<\/p>\n<p>Code:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import sys\nimport getopt def full_name(): first_name = None last_name = None argv = sys.argv[1:] try: opts, args = getopt.getopt(argv, \"f:l:\") except: print(\"Error\") for opt, arg in opts: if opt in ['-f']: first_name = arg elif opt in ['-l']: last_name = arg print( first_name +\" \" + last_name) full_name() <\/pre>\n<p>We have set arguments \u2018<code>f<\/code>\u2019 and \u2018<code>l<\/code>\u2019 for first and last name, and will pass them in the command line arguments.<\/p>\n<p>Output in command line:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">(base) PS C:\\Users\\tberr\\.vscode> py getOpt.py -f Tony -l Berry Tony Berry<\/pre>\n<p>This is certainly a lot of code to get such a simple result as <code>\u2018Full Name<\/code>\u2019, and is the reason I prefer both the <code>sys.argv<\/code> and <code>argparse<\/code> modules over <code>getopt<\/code>.\u00a0 That doesn\u2019t mean you won\u2019t find some value in the <code>getopt<\/code> module, this is simply my preference.<\/p>\n<h2><a><\/a>Summary<\/h2>\n<p>These are all powerful Python tools that can be helpful when users want to interact with your code and can make the process simple and clear.\u00a0 <\/p>\n<p>We have covered the basics here to get you started and give you an idea of a few built-in modules of Python.\u00a0 <\/p>\n<p>Good luck with your<a href=\"https:\/\/finxter.gumroad.com\/l\/finxter-premium\" target=\"_blank\" rel=\"noreferrer noopener\"> Python coding career!<\/a><\/p>\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (2 votes) In this lesson, we will learn several methods for using arguments in the command line and how we can manipulate them to run in our pre-written Python scripts. The three methods we will explore and compare are: sys.argv argparse getopt These are ordered for ease of use and simplicity.\u00a0 I\u2019ve added [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-127188","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127188","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=127188"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/127188\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=127188"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=127188"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=127188"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}