I have this code:
#!/usr/bin/python import os.path import sys if len(sys.argv)<2: print"You need to specify file!" if (os.path.isfile(sys.argv[1])): print "File <%s> exist" % sys.argv[1] elif (sys.argv[1] == "--help"): print "Add (only)one file argument to command" print "--help print this screen" print "--autor autor name and email adress" print "--about about this program" elif (sys.argv[1] == "--about"): print"Program to identify if the file exists" print"Copyright Vojtech Horanek 2015" elif (sys.argv[1] == "--autor"): print"Vojtech Horanek <vojtechhoranek@gmail.com>" else: print"No file <%s> found" % sys.argv[1]
and i want execute this piece of code only while sys.argv[1] is exist:
if (os.path.isfile(sys.argv[1])): print "File <%s> exist" % sys.argv[1] elif (sys.argv[1] == "--help"): print "Add (only)one file argument to command" print "--help print this screen" print "--autor autor name and email adress" print "--about about this program" elif (sys.argv[1] == "--about"): print"Program to identify if the file exists" print"Copyright Vojtech Horanek 2015" elif (sys.argv[1] == "--autor"): print"Vojtech Horanek <vojtechhoranek@gmail.com>" else: print"No file <%s> found" % sys.argv[1]
if i only start the program without an arguments (python program.py) it’s print this text:
You need to specify file! Traceback (most recent call last): File "program.py", line 7, in <module> if (os.path.isfile(sys.argv[1])): IndexError: list index out of range
I tried “if sys.argv == 1” but doesnt worked.
Any solutions? Thanks
Advertisement
Answer
if len(sys.argv)<2: print"You need to specify file!" sys.exit()
Now your program will terminate entirely if the user didn’t supply any arguments, rather than continuing and raising an exception.