我正在处理的程序需要暂停并要求用户输入,如果没有,请继续使用该程序。我认为它看起来像这样:
import time
...[code to run before break]...
if input in time.sleep(5):
[break out of normal code]
else:
[return to normal code]
[code to run after break]...
有什么想法吗?
编辑:当我问起但我正在运行Windows(8.1)时没想到这个。答案 0 :(得分:0)
一个快速而肮脏的黑客,但有效。以下等待用户输入5秒或直到收到输入为止,以先发生者为准。
from datetime import datetime, timedelta
import os
import signal
import threading
import time
waiting = False
def wait_and_kill(timeout):
elapsed = timedelta(0)
while elapsed.total_seconds() < timeout and waiting:
start = datetime.now()
time.sleep(0.1)
elapsed += datetime.now() - start
if waiting:
os.kill(os.getpid(), signal.SIGINT)
try:
t = threading.Thread(target=wait_and_kill, args=(5,))
waiting = True
t.start()
raw = raw_input('> ')
waiting = False
except KeyboardInterrupt:
pass