允许通过击键暂停长时间计算,然后恢复

时间:2018-01-22 21:08:46

标签: python windows keyboard interrupt

我做了很长时间(几天)的处理。我希望能够随时暂停并恢复它:

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>

1 个答案:

答案 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