我做了很长时间(几天)的处理。我希望能够随时暂停并恢复它:
while True:
do_the_work() # 100 millisec per call
if keypressed():
print "Processing paused. Please do another keypress to resume"
raw_input()
我应该使用什么功能代替伪代码keypressed()
?
显然raw_input()
在这里不起作用,因为它会在do_the_work()
的每次调用之后等待。
也使用
try: ...
except KeyboardInterrupt: ...
wouln工作,因为它会退出循环,而不是暂停/恢复。另一方面,如果try / except
在循环中,它将不会退出循环,但如果它发生在do_the_work()
的中间,则会导致问题。< / p>
答案 0 :(得分:0)
您只需要确保try/except
阻止<{1}} while
阻止。
<强>示例:强>
import time
total = 0
keep_going = True
while keep_going:
try:
total += 1
print(total)
time.sleep(1)
except KeyboardInterrupt:
try:
keep_going = input("Program is paused, type 'exit' to quit: ").lower() != 'exit'
except KeyboardInterrupt:
break
print("Program has ended").
<强>输出:强>
1
2
3
4
5
Program is paused, type 'exit' to quit: whatever
6
7
8
9
10
11
Program is paused, type 'exit' to quit: exit
Program Ending