Python中的Agrv需要多个值才能解压缩?

时间:2017-10-05 01:59:49

标签: python python-2.7 argv

我一直在关注这本书,"艰苦学习Python"作者:Zed A. Shaw。我目前正在练习18,自练习16以来一直有这个问题。我的代码是这样的:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print "Copying from %s to %s" % (from_file, to_file)

# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long %r" % len(indata)
print "Ready, hit RETURN to continues, CTRL-C to abort."
raw_input()

out_file = open(to_file, 'w')
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()

终端(macOS)中的结果是:

Traceback (most recent call last):
File "ex17.py", line 4, in <module>
script, from_file, to_file = argv
ValueError: need more than 2 values to unpack

我正在使用macOS High Serria,使用Python 2.7(非内置)在Atom中编码。

谢谢!

1 个答案:

答案 0 :(得分:0)

script, from_file, to_file = argv

这一行意味着它应该接受来自运行命令的三个值:

python test.py FileA FileB

您的脚本为test.py from_file为FileA且to_file为FileB