简体   繁体   English

如何使Python程序进入函数并在运行时使用Ctrl + X完成?

[英]How to make a Python program get into a function and finish with Ctrl+X while running?

My Python program takes a lot of time to complete all the iterations of a for loop. 我的Python程序需要花费大量时间来完成for循环的所有迭代。 The moment I hit a particular key/key combination on the keyboard while it is running, I want it to go into another method and save the variables into the disk (using pickle which I know) and exit the program safely. 当我在键盘运行时按下特定的键/键组合时,我希望它进入另一种方法并将变量保存到磁盘中(使用我知道的pickle)并安全地退出程序。

Any idea how I can do this? 知道我怎么能这样做吗?

Is the KeyboardInterrupt a safe way to this just be wrapping the for loop inside the KeyboardInterrupt exception, catching it and then saving the variables in the except block? KeyboardInterrupt是一种安全的方法,只需将for循环包装在KeyboardInterrupt异常中,捕获它然后将变量保存在except块中吗?

It is only safe if, at every point in your loop, your variables are in a state which allows you to save them and resume later. 只有在循环中的每个点上,您的变量处于允许您保存并稍后恢复的状态时才是安全的。

To be safe, you could instead catch the KeyboardInterrupt before it happens and set a flag for which you can test. 为了安全起见,您可以在它发生之前捕获KeyboardInterrupt ,并设置一个可以测试的标志。 To make this happen, you need to intercept the signal which causes the KeyboardInterrupt , which is SIGINT . 要实现这一点,您需要拦截导致KeyboardInterrupt的信号,即SIGINT In your signal handler, you can then set a flag which you test for in your calculation function. 在信号处理程序中,您可以设置一个在计算函数中测试的标志。 Example: 例:

import signal
import time

interrupted = False


def on_interrupt(signum, stack):
    global interrupted
    interrupted = True


def long_running_function():
    signal.signal(signal.SIGINT, on_interrupt)
    while not interrupted:
        time.sleep(1)   # do your work here
    signal.signal(signal.SIGINT, signal.SIG_DFL)


long_running_function()

The key advantage is that you have control over the point at which the function is interrupted. 关键优势在于您可以控制函数被中断的点。 You can add checks for if interrupted at any place you like. 您可以添加检查if interrupted你喜欢的任何地方。 This helps with being in a consistent, resumable state when the function is being interrupted. 这有助于在功能被中断时处于一致的可恢复状态。

(With python3, this could be solved nicer using nonlocal ; this is left as an excercise for the reader as the Asker did not specify which Python version they are at.) (有python3,这可能是更好的解决使用nonlocal ;这被留作因为提问者没有说明他们是在哪个Python版本读者的锻炼; Tibial。)

(This should work on Windows according to the documentation, but I have not tested it. Please report back if it does not so that future readers are warned.) (这应该在Windows上根据文档工作,但我没有测试过。如果没有,请报告,以便将来的读者收到警告。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM