Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] A Simple Guide for Using Command Line Arguments in Python

#1
A Simple Guide for Using Command Line Arguments in Python

<div>
<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;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend" style="font-size: 19.2px;"> 5/5 – (2 votes) </div>
</div>
<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 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>
<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>
<p>The three methods we will explore and compare are:</p>
<ul>
<li><code>sys.argv</code></li>
<li><code>argparse</code></li>
<li><code>getopt</code></li>
</ul>
<p>These are ordered for ease of use and simplicity.  </p>
<p>I’ve 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 – you may have a different opinion, so check it out and make your own conclusions.</p>
<h2>Method 1- sys.argv</h2>
<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 – <em>“System- specific parameters and functions.”</em></p>
<p><code>argv</code> stands for <strong><em>“argument vector”</em></strong>, and is basically a variable that contains arguments passed through the command line.</p>
<p>I’m using the VScode text editor for my scripts, as you can see in the file path, and then follow that by calling “Python” before the actual file name and arguments.  This will be the same with each method.  </p>
<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>
<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])
print('How many arguments?', len(sys.argv))
print('What are the arguments?', str(sys.argv))
</pre>
<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="">
# Adding arguments on command line
(base) PS C:\Users\tberr\.vscode> python test_command.py 3 4 5 6
</pre>
<p>Output:</p>
<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
How many arguments? 5
What are the arguments? ['test_command.py', '3', '4', '5', '6']
</pre>
<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>
<p>Now let’s do some code that is a little more involved.</p>
<p>Simple script for adding numbers with the numbers entered on the command line.</p>
<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
n = len(sys.argv)
print("Total arguments passed:", n) # Arguments passed
print("\nName of Python script:", sys.argv[0]) print("\nArguments passed:", end = " ")
for i in range(1, n): print(sys.argv[i], end = " ") # Addition of numbers
Sum = 0
# Using argparse module (we will talk about argparse next)
for i in range(1, n): Sum += int(sys.argv[i]) print("\n\nResult:", Sum)</pre>
<p>Output with arguments entered on command line:</p>
<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
Total arguments passed: 5 Name of Python script: test_command.py Arguments passed: 4 5 7 8 Result: 24</pre>
<p>This gives the user the total arguments passed, the name of the script, arguments passed (not including script name), and the “Sum” of the integers.&nbsp; Now let’s get to the<strong><em> argparse </em></strong>method.</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Note</strong>: If you are getting an ‘error’ or different results than expected when you pass arguments on the command line, make sure that the file you’re 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>
<h2>Method 2 – argparse</h2>
<p>Parser for command-line options, arguments, and sub-commands.</p>
<p><code>argparse</code> is recommended over <code>getopt</code> because it is simpler and uses fewer lines of code.</p>
<p>Code:</p>
<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
parser = argparse.ArgumentParser(description = 'process some integers.') # Adding Arguments
parser.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()
print(args.accumulate(args.integers))</pre>
<p>We see that first, we initialize the parser and then add arguments with the ‘<code>parser.add_arguments</code>’ section of the code.  </p>
<p>We also add some help messages to guide the user on what is going on with the script.  This will be very clear when we enter arguments on the command line and see our output.</p>
<p>Output:</p>
<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
usage: argparse.py [-h] N [N ...] Process some integers. positional arguments: N an integer for the accumulator accumulate sum the integers optional arguments: -h, – help show this help message and exit # Run code again without the help argument, just sum the integers.
(base) PS C:\Users\tberr\.vscode> python argParse.py 5 3 6 7
21</pre>
</p>
<p>This is an excellent, clean way to pass arguments on the command line, and the addition of the ‘<code>help</code>’ argument can make this very clear for the user.</p>
<p>For more details on arguments like [‘<code>metavar</code>’], [‘<code>const</code>’], [‘<code>action</code>’], and [‘<code>dest</code>’], 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>
<h2>Method 3 – getopt</h2>
<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>.  This is some basic code to get the name of the user on the command line.</p>
<p>Code:</p>
<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
import 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>
<p>We have set arguments ‘<code>f</code>’ and ‘<code>l</code>’ for first and last name, and will pass them in the command line arguments.</p>
<p>Output in command line:</p>
<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>
<p>This is certainly a lot of code to get such a simple result as <code>‘Full Name</code>’, and is the reason I prefer both the <code>sys.argv</code> and <code>argparse</code> modules over <code>getopt</code>.  That doesn’t mean you won’t find some value in the <code>getopt</code> module, this is simply my preference.</p>
<h2><a></a>Summary</h2>
<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.  </p>
<p>We have covered the basics here to get you started and give you an idea of a few built-in modules of Python.  </p>
<p>Good luck with your<a href="https://finxter.gumroad.com/l/finxter-premium" target="_blank" rel="noreferrer noopener"> Python coding career!</a></p>
<hr class="wp-block-separator has-alpha-channel-opacity"/>
</div>


https://www.sickgaming.net/blog/2022/08/...in-python/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016