仅在 sys.argv[1] 存在时执行代码

execute code only while sys.argv[1] exist

我有这个代码:

#!/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]

我只想在 sys.argv[1] 存在时执行这段代码:

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]

如果我只在没有参数的情况下启动程序 (python program.py) 它打印此文本:

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

我尝试了 "if sys.argv == 1" 但没有成功。

有什么解决办法吗?谢谢

if len(sys.argv)<2:
   print"You need to specify file!" 
   sys.exit()

现在如果用户没有提供任何参数,您的程序将完全终止,而不是继续并引发异常。