4

I was working off of the answer in this question: Python Interactive Shell Type Application

My code looks like this

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

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

    if s == 'exit':
      break

if __name__ == "__main__":
  main()

If I run it, and type hello, I get

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

How should I be listening for text, and calling different functions based on the result?

Community
  • 1
  • 1
rob-gordon
  • 1,419
  • 3
  • 20
  • 38
  • python my_shell.py in terminal – rob-gordon Apr 05 '13 at 18:12
  • 3
    You need [`raw_input`](http://docs.python.org/2/library/functions.html#raw_input), not [`input`](http://docs.python.org/2/library/functions.html#input) (the latter evaluates what you type as a Python expression). – Gareth Rees Apr 05 '13 at 18:13

2 Answers2

5

You're running it under Python 2.x, where input() actually evaluates what you type as a Python expression. Thus, it's looking for a variable named hello, and, since you haven't defined one, it throws the error. Either use Python 3.x, or use raw_input().

From the parentheses in your print I assume you intended to run it under Python 3.x.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • Thank you! I think I would rather force users to call defined variables, but how do I write a my own error message if they input something that is undefined? – rob-gordon Apr 05 '13 at 18:20
1
if s == 'hello':
  print('hi')

elif s == 'exit':
  break

else:
  print('Undefined input')

This should take care of undefined user input.

ThinkCode
  • 7,841
  • 21
  • 73
  • 92
  • This seems to work when using raw_input, but when using input python still throws a NameError rather than just printing 'Undefined Input' – rob-gordon Apr 05 '13 at 18:43
  • Why don't you use argparse - that is a better way of doing it imo? http://stackoverflow.com/questions/7427101/dead-simple-argparse-example-wanted-1-argument-3-results – ThinkCode Apr 05 '13 at 18:48