2013-04-05 24 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