2013-04-05 46 views
3

我工作過的回答這樣一個問題:Python Interactive Shell Type Application輸入與raw_input:Python交互式Shell應用程序?

我的代碼看起來像這樣

def main(): 
    while True: 
    s = input('> ') 

    if s == 'hello': 
     print('hi') 

    if s == 'exit': 
     break 

if __name__ == "__main__": 
    main() 

如果我運行它,然後鍵入你好,我得到

File "<string>", line 1, in <module> 
NameError: name 'hello' is not defined 

應該如何我正在聽文字,並根據結果調用不同的功能?

+0

你如何運行它? – 2013-04-05 18:10:54

+0

python my_shell.py在終端 – 2013-04-05 18:12:04

+3

您需要['raw_input'](http://docs.python.org/2/library/functions.html#raw_input),而不是['input'](http:// docs。 python.org/2/library/functions.html#input)(後者評估你輸入的Python表達式)。 – 2013-04-05 18:13:56

回答

4

您正在Python 2.x下運行它,其中input()實際上會評估您輸入爲Python表達式的內容。因此,它正在尋找名爲hello的變量變量,並且由於您沒有定義它,所以會引發錯誤。使用Python 3.x或使用raw_input()

從你的print的圓括號中,我假設你打算在Python 3.x下運行它。

+0

謝謝!我想我寧願強制用戶調用已定義的變量,但是如果他們輸入了未定義的內容,我該如何編寫自己的錯誤消息? – 2013-04-05 18:20:16

+0

使用if .. elif .. else – ThinkCode 2013-04-05 18:33:29

0
if s == 'hello': 
    print('hi') 

elif s == 'exit': 
    break 

else: 
    print('Undefined input') 

這應該照顧未定義的用戶輸入。

+0

這似乎工作時使用raw_input,但是當使用輸入python仍然會拋出一個NameError,而不是隻打印'未定義的輸入' – 2013-04-05 18:43:23

+0

爲什麼不使用argparse - 這是一種更好的方式這樣做嗎? http://stackoverflow.com/questions/7427101/dead-simple-argparse-example-wanted-1-argument-3-results – ThinkCode 2013-04-05 18:48:36