I have a "main.py" python script. I want to handle two arguments for one option when I run my script in command line.
For example, I will write the following command in my terminal:
python main.py --interval 2 4
I want to be able to get these 2 arguments (2 and 4) for this specific option (--interval) in my program.
"main.py" program:
from sys import argv
from getopt import getopt, GetoptError
try:
opts, args = getopt(argv[1:], "i:", ["interval="])
except GetoptError:
print("usage: main.py --interval <start value> <end value>")
exit(2)
for opt, arg in opts:
if opt in ("-i", "--interval"):
print("Start value: " + arg + ", end value: " + "?")
You can see in the last line of the program, I put a question mark at the place I would get the second argument for the "--interval" option.
The result I want should be:
Start value: 2, end value: 4
I know for this simple example I could just use argv[1] for the option, argv[2] and argv[3] for the arguments. But I would like to know if it is possible to do it with "getopt" library and if yes, if it is the proper way to do it.
argparse? "Users who are unfamiliar with the Cgetopt()function or who would like to write less code and get better help and error messages should consider using theargparsemodule instead."program.py --interval="2 4". Of course, your code would have to split the option. You would also need to have suitable documentation.argparsedoesn't scratch your itch.