python - "ValueError: too many values to unpack"《艰难地学习 Python》,Ex 13

标签 python python-2.7 jupyter-notebook

我使用的是 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 我在网站上输入和/或复制了确切的代码,但出现错误。

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']

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

更新: 我尝试按照建议通过终端运行它,这是我收到的响应。 enter image description here

最佳答案

正如错误所示 - ValueError: 太多值无法解压 。右侧的值太多,但左侧的名称/变量不够,无法全部接受。

在您的情况下,您的 argv 有 5 个元素,但您尝试将它们存储在 4 个元素中。我猜这与 ipython-notebook 有关。

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

python <file> <args> 

关于python - "ValueError: too many values to unpack"《艰难地学习 Python》,Ex 13,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31497579/

相关文章:

python - uWSGI 重置 PythonHome

python - 执行Python脚本的不同方式

python - 将变量添加到 ! jupyter中的命令

python - 更改非最大抑制以选择Python中OpenCV的最小框

python - Django REST Framework client.login() 不起作用。 (用户创建)

python - 收到的电子邮件附件为 'noname'

python - 从不同的源文件以编程方式诱导 IPython 笔记本输出单元

python - 在 jupyter notebook 中更改索引号

python - 通过索引替换 python 列表中的项目..失败?

python - 如何使以下文本出现在我的 python 程序中?