【问题标题】:Python unpack error need more values to unpack [duplicate]Python解包错误需要更多值来解包[重复]
【发布时间】:2015-12-16 22:10:20
【问题描述】:

我运行这段代码:

from sys import argv

script, first, second, third = argv

print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third

但是当我运行它时,我得到了这个错误:

ValueError: need more than 1 value to unpack

【问题讨论】:

  • 看来argv只有一个值。你执行了python yourscript 而不是python yourscript a b c

标签: python python-2.x


【解决方案1】:

script, first, second, third = argv 'unpacks' argv(必须包含 4 项)到相应的变量中。显然,您没有将 3 个参数传递给脚本。

试试这个来检查:

if len(argv) == 4:
    script, first, second, third = argv
else:
    print "Not enough arguments"

【讨论】:

  • 感谢帮助,但我收到一个新错误:NameError: name 'script' is not defined
  • @StubbornGoat: script 如果你没有传递 3 个参数,就不会被定义。执行路径将通过 else 子句,并且在这种情况下未定义变量。您可以将打印逻辑移到 if 子句中,也可以在 if 语句之前将变量设置为默认值。
【解决方案2】:

这意味着您没有为 python 脚本提供足够的参数。此错误意味着您尝试解压缩的值多于列表中的值。像python file.py a b c一样运行它。

试试这个代码:

if len(argv) == 4:
    script, first, second, third = argv
    print "The script is called:", script
    print "Your first variable is:", first
    print "Your second variable is:", second
    print "Your third variable is:", third
else:
    print "Not enough arguments"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多