"ValueError: too many values to unpack" in Learn Python The Hard Way, Ex 13

"ValueError: too many values to unpack" in Learn Python The Hard Way, Ex 13

我使用的是 Macbook Pro,运行 OS X Yosemite 10.10.4,正在学习 Python 艰难之路中的练习。我是 运行 这些在 iPython 笔记本上,它们的配置如下:

Python 2.7.10 |Anaconda 2.2.0 (x86_64)| (default, May 28 2015, 17:04:42) [GCC 4.2.1 (Apple Inc. build 5577)]

在 Ex13 上,在 http://learnpythonthehardway.org/book/ex13.html 上列出 我输入 and/or 复制了网站上的确切代码,但出现错误。

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 Traceback (most recent call last) in () ----> 1 script, first, second, third = argv

ValueError: too many values to unpack

我逐行尝试 运行 代码,发现问题出在我为 argv 分配了多个值时。例如,下面的代码完全执行。

from sys import argv
script = argv
print "The script is called:", script

以上代码的输出是:

The script is called: ['/Users/myusername/anaconda/lib/python2.7/site-packages/IPython/kernel/main.py', '-f', '/Users/myusername/.ipython/profile_default/security/kernel-261810c2-9f04-44d4-95f7-411e0db361ff.json', '--profile-dir', '/Users/myusername/.ipython/profile_default']

这可能是什么原因,我该如何纠正?

更新: 我按照建议通过终端尝试了 运行,这是我收到的回复。

正如错误提示的那样 - ValueError: too many values to unpack。右侧的值太多,但左侧的 names/variables 不足以接受所有值。

在您的例子中,您的 argv 有 5 个元素,但您试图将它们存储在 4 个元素中。我猜这与 ipython-notebook.

有关

您应该从命令行(终端)调用您的脚本(就像练习告诉您的那样)-

python <file> <args> 

只需从终端执行脚本,如下所示:

$> python ex13.py user_name