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.
I’ve added the getopt()
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.
Method 1- sys.argv
First, we will need to import the sys
module – “System- specific parameters and functions.”
argv
stands for “argument vector”, and is basically a variable that contains arguments passed through the command line.
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.
You can abbreviate Python as py after vscode if you wish to save on typing and that will work fine.
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))
# Adding arguments on command line (base) PS C:\Users\tberr\.vscode> python test_command.py 3 4 5 6
Output:
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']
We can see that the file name is the first argument located at the [0]
index position and the four integers are located at index[1:]
(1, 2, 3, 4) in our list of strings.
Now let’s do some code that is a little more involved.
Simple script for adding numbers with the numbers entered on the command line.
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)
Output with arguments entered on command line:
(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
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. Now let’s get to the argparse method.
💡 Note: 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 saved. If your Python file has been changed or is new it will not work until you do so.
Method 2 – argparse
Parser for command-line options, arguments, and sub-commands.
argparse
is recommended over getopt
because it is simpler and uses fewer lines of code.
Code:
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))
We see that first, we initialize the parser and then add arguments with the ‘parser.add_arguments
’ section of the code.
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.
Output:
# 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
This is an excellent, clean way to pass arguments on the command line, and the addition of the ‘help
’ argument can make this very clear for the user.
For more details on arguments like [‘metavar
’], [‘const
’], [‘action
’], and [‘dest
’], check out this LINK
Method 3 – getopt
A method for parsing command line options and parameters, very similar to the getopt()
function in the C language. This is some basic code to get the name of the user on the command line.
Code:
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()
We have set arguments ‘f
’ and ‘l
’ for first and last name, and will pass them in the command line arguments.
Output in command line:
(base) PS C:\Users\tberr\.vscode> py getOpt.py -f Tony -l Berry Tony Berry
This is certainly a lot of code to get such a simple result as ‘Full Name
’, and is the reason I prefer both the sys.argv
and argparse
modules over getopt
. That doesn’t mean you won’t find some value in the getopt
module, this is simply my preference.
Summary
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.
We have covered the basics here to get you started and give you an idea of a few built-in modules of Python.
Good luck with your Python coding career!