2011-11-01 26 views
6
import sys 

    print sys.argv[1] 

喜,Python將無法讀取sys.argv中

這可能看起來很基本的,但我不能讓Python在命令行任何讀取。 那上面的代碼和我的類型是:

myfile.py helloworld 

和我得到的回覆是:

IndexError: list index out of range 

這似乎是一次對我的工作,但不會工作了,而且我已經嘗試卸載並重新安裝Python,它仍然無法正常工作。

所以我的問題是,我做錯了什麼?或者我剛破壞Python?

感謝所有幫助

使用: Windows 7的 的Python 2.7.2

+0

會發生什麼事時,你只是'打印sys.argv'?當它通過'python.exe myfile.py helloworld'調用文件時它工作嗎? – poke

+0

啊,謝謝你的迴應,設法讓它工作。 有一個非常愚蠢的錯誤,沒有將Python添加到系統變量中的路徑 – user1024028

+0

對於那些在Windows中將參數傳遞給腳本而無法將其與Python調用相掛鉤的問題(例如'python foo.py a'工作但foo。 py a'沒有,)滾過第一個答案。 – eenblam

回答

5

你確定你在呼喚你的Python腳本你認爲你現在的樣子?

#!/usr/bin/python 
import sys 

if len(sys.argv) < 2: 
    print "you did not give any arguments\n" 
else: 
    print sys.argv[1] 

回報:

$ ./foo.py 
you did not give any arguments 

$ ./foo.py hello_world 
hello_world 
$ 
+0

感謝您的迴應,設法讓它工作 – user1024028

11

啓動註冊表編輯器(regedit)。設置HKEY_CLASSES_ROOT \應用程序\ python26.exe \殼\開放\命令關鍵:該解決方案的 "C:\Python26\python26.exe" "%1" %*

來源:http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/

+2

哇,今天這個註冊表遺漏了我們,我們試圖平衡一個Python 2.7 Anaconda和3.4安裝並排。 3.4安裝程序省略了'%*'參數,但我們需要爲'HKEY_CLASSES_ROOT \ Applications \ pythonxx.exe \ shell \ open \ command'鍵以及'HKEY_CLASSES_ROOT \ py_auto_file \ shell \ open \ command '鍵 – jxramos

+0

感謝您的回答 –