I'm creating a menu driven python script but I also want to add the functionality for command line arguments, for example if user has to select 2nd option he can either do it normal way i.e pressing 2 when asked to enter choice or to directly choose 2 by passing command line argument.
For this, am using sys
module. And checking if user has passed any command line argument if not, then calling the function which would print the options and ask user to enter his choice (the normal way as mentioned above)
As per example command would be $ python3 choice.py 2
But am getting error while doing this and can't figure out what is wrong, here is the way am doing.
import sys
.
.
.
if sys.argv[2]:
if sys.argv1[2] == 1:
choose_one()
elif sys.argv[2] == 2:
choose_two()
elif sys.arg[2] == 3:
choose_three()
else:
choose_option() #If none of these command line args then call the function which would print options and let user choose
Error:
File "choice.py", line 3, in <module>
if sys.argv[2]:
IndexError: list index out of range
Basically I am willing to give user both options if he wants to run things quickly he can pass command line arguments, bypassing the usual reading choice option and entering the choice.