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?

1 Answer 1

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...)

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Glad it helped! Ignore my bit about the threading module. I was way off base, there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.