【问题标题】:Allow to pause a long computation with a keystroke, and resume允许通过击键暂停长时间的计算,并恢复
【发布时间】:2018-01-22 21:08:46
【问题描述】:

我正在进行长时间(几天)的处理。我希望能够随时暂停并恢复它:

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() 中间会导致问题。

【问题讨论】:

  • 您可以写入文件并让您的代码定期检查该文件。
  • > using a try/except would exit the loop 如果它在循环内,则不会。不过,它可能会从 do_the_work() 函数中引发并导致问题。
  • @PedrovonHertwig:是的,如果它在do_the_work() 的中间提出,它会引起问题。我编辑了 OP 以提及这一点。

标签: python windows keyboard interrupt


【解决方案1】:

您只需要确保您的 try/except 位于 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

【讨论】:

  • 假设do_the_work() 持续 1 秒。如果用户在do_the_work() 开始后 0.5 秒按 CTRL+C,则此调用将被中断并且永远不会在此处恢复。计算将在下一次调用 do_the_work() 时恢复,因此会损失 0.5 秒的工作时间。
  • 没有在调试器控制台上运行它,我没有想法,抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-03-06
  • 1970-01-01
  • 2017-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
相关资源
最近更新 更多