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

2024-04-20 10:21:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个长的(几天的)处理。我希望能够随时暂停并继续:

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

不起作用,因为它会退出循环,而不是暂停/继续。另一方面,如果try / except循环中,它不会退出循环,但是如果它发生在do_the_work()的中间,它会引起问题。你知道吗


Tags: thetrueinputrawifcalldowork
1条回答
网友
1楼 · 发布于 2024-04-20 10:21:19

你只需要确保你的try/exceptwhile块中。你知道吗

示例:

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

相关问题 更多 >