我正在Windows7上使用cmd.exe通过此行执行python脚本:
> csv_cleaner.py ../test.csv ../oui.csv
脚本的第一行是:
import configparser, csv, sys
if len(sys.argv) < 3 :
usage = """Usage: %s [inputfile][output file]\nThis program requires 2 \
arguments to function properly.\n[input file] is the file to clean\n[output fil\
e] is the name of the file that will be created as a result of this
program\n"""
print(usage % (sys.argv[0]))
else :
问题是,无论我通过检查的参数有多少总是失败,此外,当我尝试打印除第一个参数之外的任何参数时,都会收到此错误。
File "C:\Users\comte\Desktop\csv_cleaner\csv_cleaner.py", line 3, in <module>
print(sys.argv[2])
IndexError: list index out of range
len(sys.argv)
返回1
答案 0 :(得分:0)
如果您尝试访问sys.argv
列表中不存在的项目,Python会抛出IndexError异常。
相反,如果要检查已将多少参数传递给cammand行,可以使用len(sys.argv)
:
if len(sys.argv) <= 2 :
usage = """Usage: %s [inputfile][output file]\nThis program requires 2 \
arguments to function properly.\n[input file] is the file to clean\n[output fil\
e] is the name of the file that will be created as a result of this
program\n"""
print(usage % (sys.argv[0]))
答案 1 :(得分:0)
问题似乎是来自我PATH中卸载的python2的人工产物。
现在将其删除,一切正常。