我有这个密码:

#!/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 <[email protected]>"
else:
  print"No file <%s> found" % sys.argv[1]

我想只在Ssys .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 <[email protected]>"
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()

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

关于python - 仅在sys.argv [1]存在时执行代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30484409/

10-15 08:35