如何从外部停止执行 Python 函数?

How can I stop the execution of a Python function from outside of it?

所以我使用了这个库,并且在我的一个函数中调用了该库中的一个函数,这恰好需要很长时间。现在,同时我有另一个线程 运行ning,我在其中检查不同的条件,我想要的是如果满足条件,我想取消库函数的执行。

现在我正在检查函数开始时的条件,但是如果条件在库函数 运行ning 期间发生变化,我不需要它的结果,并且想要return来自它。

基本上这就是我现在所拥有的。

def my_function():
    if condition_checker.condition_met():
        return
    library.long_running_function()

有没有办法 运行 每秒检查一次条件,并在满足条件时从 my_function return 开始?

我考虑过装饰器、协同程序,我正在使用 2.7,但如果这只能在 3.x 中完成,我会考虑切换,只是我不知道如何。

您不能终止线程。图书馆支持设计取消,如果请求,它内部必须每隔一段时间检查一次条件以中止,或者您必须等待它完成。

您可以做的是在子进程而不是线程中调用库,因为进程可以通过信号终止。 Python 的 multiprocessing 模块提供类似线程的 API 用于生成分叉和处理 IPC,包括同步。

或者如果分叉对您的资源造成太大负担(例如,通过复制父进程占用内存),则通过 subprocess.Popen 生成一个单独的子进程。

不幸的是,我想不出任何其他方法。

一般来说,我想你想 运行 你的 long_running_function 在一个单独的线程中,让它偶尔向主线程报告它的信息。

This post 在 wxpython 程序中给出了一个类似的例子。

假设您在 wxpython 之外执行此操作,您应该能够将 wx.CallAfter 和 wx.Publisher 替换为 threading.Thread and PubSub

看起来像这样:

import threading
import time

def myfunction():
    # subscribe to the long_running_function
    while True:
        # subscribe to the long_running_function and get the published data
        if condition_met:
            # publish a stop command
            break
        time.sleep(1)

def long_running_function():
    for loop in loops:
        # subscribe to main thread and check for stop command, if so, break
        # do an iteration
        # publish some data

threading.Thread(group=None, target=long_running_function, args=())  # launches your long_running_function but doesn't block flow
myfunction()

我没有经常使用 pubsub,所以我不能快速编写代码,但它应该可以帮助你。

或者,您是否知道启动 long_running_function 之前的停止条件?如果是这样,你可以将它作为参数传递并检查它是否在内部得到满足。