【问题标题】:input vs. raw_input: Python Interactive Shell Application?输入与 raw_input:Python 交互式 Shell 应用程序?
【发布时间】:2013-03-28 06:23:30
【问题描述】:

我正在解决这个问题的答案:Python Interactive Shell Type Application

我的代码是这样的

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

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

    if s == 'exit':
      break

if __name__ == "__main__":
  main()

如果我运行它并输入 hello,我会得到

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

我应该如何监听文本,并根据结果调用不同的函数?

【问题讨论】:

  • 终端中的python my_shell.py
  • 您需要raw_input,而不是input(后者将您键入的内容作为 Python 表达式求值)。

标签: python shell undefined interactive


【解决方案1】:
if s == 'hello':
  print('hi')

elif s == 'exit':
  break

else:
  print('Undefined input')

这应该处理未定义的用户输入。

【讨论】:

  • 这似乎在使用 raw_input 时有效,但是在使用 input 时 python 仍然会抛出 NameError 而不仅仅是打印'Undefined Input'
  • 你为什么不使用 argparse - 这是 imo 的更好方法? stackoverflow.com/questions/7427101/…
【解决方案2】:

您在 Python 2.x 下运行它,input() 实际上将您键入的内容计算为 Python 表达式。因此,它正在寻找一个名为hello变量,并且由于您尚未定义一个变量,因此它会引发错误。要么使用 Python 3.x,要么使用raw_input()

print 的括号中,我假设您打算在 Python 3.x 下运行它。

【讨论】:

  • 谢谢!我想我宁愿强迫用户调用已定义的变量,但是如果他们输入了未定义的内容,我该如何编写自己的错误消息?
猜你喜欢
  • 2012-06-09
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-23
  • 2011-09-13
  • 1970-01-01
  • 2013-05-06
相关资源
最近更新 更多