I've been attempting to make the sys.argv[] to either change its output according to the number of argument that the user input. I am trying to make it so that if there is no sys.argv[5] then it would use sys.argv[4]. Currently I have tried both this ideas with my problem always IndexError: list index out of range when I do attempt to make sys.argv[5] left empty:
if len(sys.argv) is 4:
location = int(sys.argv[1])
order = sys.argv[2]
amount = sys.argv[3]
user = sys.argv[4]
company= sys.argv[4]
print(company)
else:
location = int(sys.argv[1])
order = sys.argv[2]
amount = sys.argv[3]
user = sys.argv[4]
company= sys.argv[5]
print(company)
also attempted to change "if len(sys.argv) is 4:" with "if sys.argv[5] != True:". I've read some posting about solving the index but just don't know how to actually tailor the code for my own use.
Thanks!
CodePudding user response:
You can use try/except
block like below, where if index 5
is present use it, else use index 4
.
if len(sys.argv) >= 4:
location = int(sys.argv[1])
order = sys.argv[2]
amount = sys.argv[3]
user = sys.argv[4]
try:
company= sys.argv[5]
except IndexError:
company= sys.argv[4]
print(company)
else:
print('Provide minimum 4 args')