尝试循环sys.args
时,我收到以下错误:
Traceback (most recent call last):
File "./autoCrosRef.py", line 59, in <module>
cleanFile(inputArgs[i])
TypeError: list indices must be integers, not str
这就是我调用程序的方式:
./autoCrosRef.py file.txt
这是我用来尝试循环的代码:
import sys
# ------
# MAIN
# ------
inputArgs = sys.argv
print len(inputArgs)
for i in inputArgs[1:]:
cleanFile(inputArgs[i])
我的打印命令显示我在cmd处传递2个args但是它一直出错,我调用错了还是我的循环错了?
答案 0 :(得分:4)
i
inputArgs数组中有一个项目 - 而不是索引。你可以做
for i in range(1, len(inputArgs)):
# i is a number, from 1 to len(inputArgs)-1
cleanFile(inputArgs[i])
或(这是首选)
for i in inputArgs[1:]:
# i is an item from inputArgs. If inputArgs=['foo', 'bar', 'baz']
# then i is first 'bar' then 'baz'.
cleanFile(i)