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
lin开发者_如何学Pythone. 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?
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...)
精彩评论