2

I'm writing a simple dual timer in Python. (I'm running Linux, and this should only need to run on my system.) The idea is that the script has two separate timers, one of which is running at any one time. The user should be able to press a button to either switch which timer is running, or pause both. Currently, the test script looks like this:

now = datetime.datetime.now()
until = now + datetime.timedelta(minutes=2)
print now,
while now < until:
    print "\r",
    now = datetime.datetime.now()
    print now,
    sys.stdout.flush()
    # check stdin here
    time.sleep(0.1)

(I've skipped the imports in the code here.)

This outputs the current value of the timer to stdout every 0.1 seconds, overwriting the previous value when it does so.

I'm having problems, however, working out how to implement the # check stdin here line. Ideally, the user should just be able to press, say, "p", and the timer would be paused. At the moment, I have this in place of time.sleep(0.1):

if select.select([sys.stdin],[],[],0.1)[0]:
    print sys.stdin.readline().strip()

...which works, except that it requires the user to press enter for a command to be recognised. Is there a way of doing this without needing enter to be pressed?

Sam
  • 439
  • 5
  • 10

1 Answers1

2

See this SO question and this article.

Both of those describe either platform-specific options or using something like pygame.

However, if you need a cross-platform solution that doesn't require any external dependencies (e.g. pygame), I think you should also be able to do it through the threading module in the standard library. (Give me a bit and I'll try to cobble something using the threading module together...)

Community
  • 1
  • 1
Joe Kington
  • 275,208
  • 71
  • 604
  • 463
  • 1
    The "Python non-blocking console input on Linux" solution described in the article works perfectly for my needs, thanks! I don't need any cross-platform compatibility here. Someone else suggested using curses, which also works, because curses by default sets the same mode as set using the termios method. The termios method doesn't change any other settings, however, which curses does, so it's neater. – Sam May 20 '10 at 17:39
  • Glad it helped! Ignore my bit about the threading module. I was way off base, there. – Joe Kington May 20 '10 at 19:02