I am trying to add command line options to program. The program should accept both a list of numbers, and parse options. For instance a call to the program could look like:
python3 ./parsetest.py 4 3 v=100
The 4 and the 3 will be processed in one way whereas the v=100 command will set the internal variable v to 100. I found the getopt library is supposed to have this functionality: http://stackabuse.com/command-line-arguments-in-python/ Is there a better/simpler way to do this?
When I try to parse the input like the above, I believe getopt should place arguments which trigger its keywords into a special list, and those which do not trigger are placed elsewhere. However, when I try to use getopt following the example above, no matter what I do, the v=100 option does not appear to trigger the special arguments list. When passed to getopt, I expected the 'v=100' string to be split up into argument v and value 100. For instance, the print(arguments,values) command below results in: [] ['4', '3', 'v=100']. There are values, but there are no arguments.
Here is my code:
import sys,getopt
v = 1e100
fullCmdArguments = sys.argv
argumentList = fullCmdArguments[1:]
unixOptions = "v:"
gnuOptions = ["v="]
print(argumentList)
try:
arguments, values = getopt.getopt(argumentList, unixOptions, gnuOptions)
except getopt.error as err:
# output error, and return with an error code
print (str(err))
sys.exit(2)
print(arguments, values)
for currentArgument, currentValue in arguments:
print (currentArgument, currentValue)
if currentArgument in ("-v", "v"):
v = currentValue
else:
#Its an integer then, do something with it
print()
If you can use argparse
the following will work:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('numbers', type=int, nargs='+')
parser.add_argument('-v', type=int, default=-1)
args = parser.parse_args()
print(args.numbers)
print(args.v)
# due to the default set above, `args.v` will always have an int value
v = args.v
Using the nargs
keyword argument you can set it to '+' requiring one or more numbers. The v
with a hyphen is by default optional. If this is not wanted, you can add the required=True
option.
python my_file.py 1 2 3 5 -v=12
[1, 2, 3, 5]
12
python my_file.py 1 2 3 5
[1, 2, 3, 5]
-1
For more information about the argparse module you can have a look at: