Python: using keyboard input in a continuous loop?

The OS is a Redhat-clone Linux distribution, I use python-2.x.

General code structure:

# 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 allow the user to control the program by pressing various keys. For example, "press S to shut down remote devices correctly, K to kill, R to reboot." All these actions should take place inside a large cycle - the comment “maybe do something or just watch” in my pseudo-code. If no key is pressed, the program should simply continue the cycle.

I'm not sure how to read from the keyboard in the context of the True: time.sleep (1) loop.

+4
source share
3 answers

, - curses; , , ( , /usr/bin/clear ncurses-bin Ubuntu), Enter , .

, , , . clear(1) , .

+1

.

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")
+1
0

All Articles