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

时间:2015-05-27 13:47:23

标签: python linux if-statement sys

我有这段代码:

#!/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”但是没有用。

任何解决方案?谢谢

1 个答案:

答案 0 :(得分:3)

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

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