Define the class to read arguments
To use arguments passed by parameter in a Python script you can use the following library
from argparse import ArgumentParser import sys # ArgumentParser with a description of the application parser = ArgumentParser(description='%(prog)s is an ArgumentParser demo')
Example of required arguments
# Positional argument with description parser.add_argument('file', help='help of file')
Example of optional arguments
# Positional argument. If it is parameterized, it requires an integer value # (Https://docs.python.org/3/library/argparse.html#type) parser.add_argument('value', help='help for opt3', type=int) # Positional argument with three possible options, can be called with -f or -fruit # (Https://docs.python.org/3/library/argparse.html#choices) parser.add_argument('-f','--fruit', choices=['pears', 'apples', 'oranges']) # Optional argument with description. If parameter requires integer, default is 10 parser.add_argument('-v', help='help for opt4', type=int, default=10) # Optional argument. With ' action ' we value if the argument is parameterized # (Https://docs.python.org/3/library/argparse.html#action) parser.add_argument('-op1', '--option1', help='help for opt5', action='store_true', default=False) # Optional argument that requires two arguments parser.add_argument('-op2', nargs=2) # Optional argument that requires 1 to N arguments parser.add_argument('-op3', nargs='+') # Optional argument that requires 0 to N arguments parser.add_argument('-op4', nargs='*')
Reading arguments in code
# Finally parse the arguments args = parser.parse_args()
# Print parameter print ('File:', args.file) print ('Integer number:', args.value) print ('Fruit choise:', args.fruit) print ('Value choise:', args.v) print ('Option 1:', args.option1) print ('Option 2:', args.op2) print ('Option 3:', args.op3) print ('Option 4:', args.op4) # get input data: if args.file != None: print("\n\nInput file: " + args.file ) inputfile = args.file else: sys.stderr.write("Please, Specify a file!\n") sys.exit(2)
Running Python scripts with arguments
All the content described above is saved in a file called “prueba.py” and when executing it, it would give us the following output that shows the correct functioning.
> test.py file.txt 2
File: file. txt Integer parsed number: 2 Select fruits: None Select Value: 10 Option 1: False Option 2: None Option 3: None Option 4: None Input file: file.txt
0 Comments