【问题标题】:Agrv in Python Needs More Than One Value to Unpack?Python 中的 Agrv 需要多个值来解包?
【发布时间】:2017-10-05 10:05:37
【问题描述】:

我一直在关注 Zed A. Shaw 的书“Learn Python the Hard Way”。我目前在练习 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 中编码。

谢谢!

【问题讨论】:

  • 你是如何运行它的?看起来你没有提供足够的论据。
  • 看来 atom 只传递了第一个参数。您还需要指定 to_file 参数,例如 python ex18.py path/to/from_file.txt path/to/to_file.txt

标签: python python-2.7 argv


【解决方案1】:
script, from_file, to_file = argv

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

python test.py FileA FileB

您的脚本在哪里 test.py from_file 是 FileA 而 to_file 是 FileB

【讨论】:

  • 谢谢!这对我有用!再次,非常感谢!
  • 您应该将答案标记为 Accepted ,因为它有助于结束问题(stackoverflow 上的常见做法)
  • 谢谢你,iamdeowanshi,你告诉我。我是新用户,谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-03
相关资源
最近更新 更多