![]() |
|
[Tut] A Simple Guide for Using Command Line Arguments in Python - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] A Simple Guide for Using Command Line Arguments in Python (/thread-99806.html) |
[Tut] A Simple Guide for Using Command Line Arguments in Python - xSicKxBot - 08-14-2022 A Simple Guide for Using Command Line Arguments in Python 5/5 – (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:
These are ordered for ease of use and simplicity. I’ve added the Code: getopt()Method 1- sys.argv First, we will need to import the Code: sysCode: argvI’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. Code: 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))Code: # Adding arguments on command line
(base) PS C:\Users\tberr\.vscode> python test_command.py 3 4 5 6Output: Code: 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 Code: [0]Code: index[1:]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. Code: 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: Code: (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: 24This 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. Code: argparseCode: getoptCode: 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 ‘ Code: parser.add_argumentsWe 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: Code: # 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
21This is an excellent, clean way to pass arguments on the command line, and the addition of the ‘ Code: helpFor more details on arguments like [‘ Code: metavarCode: constCode: actionCode: destMethod 3 – getopt A method for parsing command line options and parameters, very similar to the Code: getopt()Code: 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 ‘ Code: fCode: lOutput in command line: Code: (base) PS C:\Users\tberr\.vscode> py getOpt.py -f Tony -l Berry Tony BerryThis is certainly a lot of code to get such a simple result as Code: ‘Full NameCode: sys.argvCode: argparseCode: getoptCode: getoptSummary 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 yourPython coding career! |