我正在通过https://testdriven.io/developing-an-asynchronous-task-queue-in-python工作。我还查看了sys.argv[1] meaning in script以便对sys.argv进行澄清
从前者我有:
def save_file(filename, data):
random_str = uuid.uuid4().hex
outfile = f'{filename}_{random_str}.txt'
with open(os.path.join(OUTPUT_DIRECTORY, outfile), 'w') as outfile:
outfile.write(data)
def get_word_counts(filename):
wordcount = collections.Counter()
# get counts
with open(os.path.join(DATA_DIRECTORY, filename), 'r') as f:
for line in f:
wordcount.update(line.split())
for word in set(COMMON_WORDS):
del wordcount[word]
# save file
save_file(filename, json.dumps(dict(wordcount.most_common(20))))
# simulate long-running task
time.sleep(2)
proc = os.getpid()
print(f'Processed {filename} with process id: {proc}')
if __name__ == '__main__':
print(sys.argv, len(sys.argv))
# print(sys.argv[1], len(sys.argv))
get_word_counts(sys.argv[1])
当我直接运行它时,会得到:
$ python tasks.py
['tasks.py'] 1
Traceback (most recent call last):
File "tasks.py", line 46, in <module>
get_word_counts(sys.argv[1])
IndexError: list index out of range
鉴于您可以看到列表中只有一个元素,为什么作者以这种方式编写代码?
答案 0 :(得分:1)
get_word_counts(sys.argv[1])
应该是
get_word_counts(sys.argv[0])
在大多数语言(包括python)中,索引均从零开始