I am trying to make a prompt in Python 2.7. I have an infinite loop that will get the user's input using str(raw_input('$> '))
. Then, it checks a bunch of 'if' and 'elif' statements (each one is a particular command) to see what to do with the entered command. I have also disabled KeyboardInterrupt through a 'try... except' statement, and added an 'exit' command. Here is where the problem lies. The 'exit' command runs well, printing 'Bye' and then quitting. However, so does every other unknown command.
I have tried using the built-in quit()
and exit()
functions and sys.exit()
, but none of them fix the problem. I have also encased my 'if' statements in a while loop that checks if it is not the 'exit' command, and then used the else statement to quit. However, it just prints Command "exit" not found.
My question is a) why Python will execute that code for any statements after it, and b) what to do to fix this, if possible.
My theory for a) is that because Python is interpreted line by line, it reads that line and for whatever reason, executes it. However, if the command matches, it stops looking at the 'if' statement and executes the code for the entered command.
Here is a simplified version of my code, and thank you in advance.
from sys import exit as die
while True:
msg = str(raw_input('$> '))
if msg == 'test':
print '123'
elif msg == 'quit' or 'exit':
print 'Bye'
die()
elif msg == 'test2':
print '456'
else:
print 'Command "%s" not found' % (msg)
If I run the 'test2' command, or an unkown command 'foo', the program will print 'Bye' and exit.