【发布时间】:2015-07-19 02:56:33
【问题描述】:
我使用的是 Macbook Pro,运行 OS X Yosemite 10.10.4,并且正在完成 Learn Python the Hard Way 中的练习。我在 iPython 笔记本上运行这些,它们的配置如下:
Python 2.7.10 |Anaconda 2.2.0 (x86_64)| (默认,2015 年 5 月 28 日, 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(最近调用 最后)在() ----> 1 个脚本,第一个,第二个,第三个 = argv
ValueError:解包的值太多
我尝试逐行运行代码,发现问题出在我为 argv 分配多个值时。例如,下面的代码完全执行。
from sys import argv
script = argv
print "The script is called:", script
上述代码的输出是:
脚本被调用: ['/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']
这可能是什么原因,我该如何纠正它?
更新: 我尝试按照建议通过终端运行它,这就是我收到的响应。
【问题讨论】:
-
你应该从命令行调用它,就像他们告诉你的那样。不要在这个练习中使用 ipython。
-
基本上问题是您有 4 个参数,但您的脚本需要 3 个。尝试在您的元组解包之前放置一个
print(len(argv))并查看结果如何。如果那不是 4,那么您将遇到问题。第二个代码 sn -p 将打印整个argv而不管参数的数量,因此不是问题。 -
谢谢,但这是 ipython 笔记本的限制,代码可以通过终端运行,但在使用笔记本时不能运行?
-
嗯,只是您需要通过命令行传递代码参数,并且至少在我的计算机上 ipython 试图打开我作为文件传递的参数,这导致它出错: P
-
Invoke你的脚本来自终端(不是 python 终端),命令行终端。 (并且不要在那里编写代码),首先将其保存为脚本,然后调用该脚本。
标签: python python-2.7 ipython-notebook