I have a Python
script that requires at least one command line argument to run with default values. I want to allow the user to optionally change these default values from the command line.
Right now, I run it with python script.py arg1
and it works great but I want to be able to run it with python script.py arg1 [optional arg2 optional arg3]
.
Also to clarify, I'm using the following block of code to check for number of agreements and to print some information:
if len(sys.argv) < 2:
print "Error. Required: python "+sys.argv[0]+" arg1 + [optional] arg2 (default 2) + [optional] arg3 (default 100)"
sys.exit(0)
After that, I tried the following:
if sys.argv[2] == None:
default_value1 == 2
else:
default_value1 == sys.argv[2]
if sys.argv[3] == None:
default_value2 == 100
else:
default_value2 == sys.argv[3]
I also tried replacing the None
above for an empty string (""
) or a space (" "
) but I always get the error:
if sys.argv[2] == None:
IndexError: list index out of range
How do you allow for additional sys.argv
to be passed or ignored on the command line? I think to understand that I would have to either give it both additional arguments (i.e.,sys.argv[2]
and sys.argv[3]
) or none at all for the above code to work. Is this correct?
Thanks!