python: using keyboard input in a continuous loop? [duplicate]
The OS is a Redhat-clone Linux distribution, I'm using python-2.x.
General code structure is:
# stuff is initialized
while True:
# read stuff from remote devices
# process data
# maybe do stuff, or maybe just watch
os.system("clear")
# display status of remote devices
time.sleep(1)
I want to let the user drive the program by pressing various keys. E.g. "press S to gracefully shutdown remote devices, K to kill, R to restart". All those actions need to happen inside the big loop - the "maybe do stuff, or maybe just watch" comment in my pseudo-code. If no key is pressed, the program should just keep looping.
I'm not sure how to accomplish the keyboard reading within the context of a while True: time.sleep(1) loop.
Probably the easiest way there is to use curses; it lets you clear the screen without resorting to an external program that may or may not exist (though funny enough, /usr/bin/clear
is provided by the ncurses-bin
package on my Ubuntu system), it makes listening for a keystroke without an Enter press easy, and it makes placing text at specific locations on screen pretty easy.
The downside to using curses is that programs that use it are hard to use in pipelines. But if you're calling clear(1)
from inside your program already, pipelines are already not really an option.
The following code works fine for me.
while True:
choice = raw_input("> ")
choice = choice.lower() #Convert input to "lowercase"
if choice == 'exit':
print("Good bye.")
break
if choice == 'option1':
print("Option 1 selected")
if choice == 'option2':
print("Option 2 selected")
精彩评论