【问题标题】:How can I stop the execution of a Python function from outside of it?如何从外部停止 Python 函数的执行?
【发布时间】:2015-03-06 19:52:45
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

  • 我唯一能想到的就是偶尔检查一下在长时间运行的函数中是否满足条件。如果它是某种很容易打破的循环,但我确信有更好的解决方案。

标签: python function exit


【解决方案1】:

您不能终止线程。要么库支持按设计取消,它在内部必须每隔一段时间检查一次条件以在请求时中止,或者你必须等待它完成。

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

如果分叉对您的资源来说过于繁重(例如,通过复制父进程占用内存),或者通过 subprocess.Popen 生成一个单独的子进程。

很遗憾,我想不出其他办法。

【讨论】:

  • 因此在 my_function 中,我将使用库函数启动一个子进程,然后等待条件检查器中的条件得到满足(然后停止库函数)或等待长时间运行的函数在我从我的职能返回之前完成。我认为这会起作用,谢谢。
【解决方案2】:

一般来说,我认为您希望在单独的线程中运行您的long_running_function,并让它偶尔向主线程报告其信息。

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

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

看起来像这样:

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 之前的停止条件?如果是这样,您可以将其作为参数传递并检查内部是否满足。

【讨论】:

  • 遗憾的是我无法访问 long_running 函数,在这种情况下我想我可以,但我想要一个不涉及更改库的更通用的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-12
相关资源
最近更新 更多