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

时间:2015-03-06 19:52:46

标签: python function exit

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

现在我正在检查函数开头的条件,但是如果在库函数运行时条件发生变化,我不需要它的结果,并希望从它返回。

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

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

有没有办法每隔一秒左右运行条件检查,并在满足条件时从my_function返回?

我已经考虑过装饰器,协同程序,我正在使用2.7但如果这只能在3.x中完成,我会考虑切换,这只是我无法弄清楚如何。

2 个答案:

答案 0 :(得分:3)

您无法终止线程。这个库可以支持设计取消,内部必须每隔一段时间检查一个条件,如果请求就中止,或者你必须等待它完成。

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

如果forking对您的资源过重(例如通过复制父进程的内存占用量),则通过subprocess.Popen生成一个单独的子进程。

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

答案 1 :(得分:0)

通常,我认为你想在一个单独的线程中运行你的long_running_function,并偶尔将它的信息报告给主线程。

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

假设您在wxpython之外执行此操作,您应该能够使用threading.ThreadPubSub替换wx.CallAfter和wx.Publisher。

它看起来像这样:

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之前知道停止标准吗?如果是这样,您可以将其作为参数传递,并检查它是否在内部得到满足。