2015-07-19 84 views
1

我正在使用Macbook Pro,運行OS X Yosemite 10.10.4,並且正在完成Learn Python Hard Work中的練習。我在IPython的筆記本電腦上運行這些,他們的配置是如下:「ValueError:太多的值解壓縮」在學習Python困難的方式,例如13

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

+0

你應該調用它來自命令行,完全是他們告訴你的方式。這個練習不要使用ipython。 – NightShadeQueen

+0

基本上這個問題是你有4個參數,但你的腳本期望3.試着在你的元組解開之前放一個'print(len(argv))',看看結果是什麼。如果那是4以外的任何東西,你將會遇到問題。第二個代碼片段將打印整個'argv',而不管參數的數量如何,因此不成問題。 – shuttle87

+0

謝謝,但這是ipython筆記本電腦的限制,代碼將通過終端工作,但不是在使用筆記本時? – user2762934

回答

1

它作爲錯誤提示 - ValueError: too many values to unpack。右側的值太多,但左側沒有足夠的名稱/變量來接受它們。

就你而言,你的argv有5個元素,但你試圖將它們存儲在4個元素中。我猜這是與ipython-notebook相關的。

你應該調用命令行(終端)腳本(就像鍛鍊告訴你) -

python <file> <args> 
0

剛剛從終端執行腳本象下面這樣:

$> python ex13.py user_name 
相關問題