6

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.

Florin Andrei
  • 1,067
  • 3
  • 11
  • 33
  • see http://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python – Bala R Jun 09 '11 at 00:48
  • Have you looked at the `curses` module? – tMC Jun 09 '11 at 00:49
  • Almost everyone got this wrong. `curses` is a usable tool for the job, but simply linking the documentation isn't an answer. More to the point, the problem isn't with figuring out how to read input, but how to make a *non-blocking call* to read input. – Karl Knechtel Feb 06 '23 at 09:53

2 Answers2

1

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.

sarnold
  • 102,305
  • 22
  • 181
  • 238
  • 2
    if you don't want to depend on the `clear` command, you can just print the ANSI code from python: `print "\33[H\33[2J"`. FWIW – tMC Jun 09 '11 at 01:05
0

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")
Luis Jose
  • 664
  • 6
  • 8