[英]How can I stop the execution of a Python function from outside of it?
因此,我有一个要使用的库,并且在我的一个函数中,我从该库中调用一个函数,而这恰好需要很长时间。 现在,同时我有另一个线程正在运行,以检查不同的条件,我想要的是,如果满足条件,我想取消执行库函数。
现在,我正在检查函数启动时的条件,但是如果条件在库函数运行时发生了变化,则不需要其结果,而是要从中返回。
基本上这就是我现在所拥有的。
def my_function():
if condition_checker.condition_met():
return
library.long_running_function()
有没有办法每秒运行一次条件检查,并在满足条件时从my_function返回?
我考虑过装饰器,协程,我使用的是2.7,但是如果只能在3.x中完成,则我会考虑进行切换,只是我不知道如何操作。
您不能终止线程。 库要么通过设计支持取消,要么在内部必须每隔一段时间检查一次条件以中止请求(如果需要),或者必须等待它完成。
您可以做的是在子进程而不是线程中调用库,因为可以通过信号终止进程。 Python的multiprocessing
模块提供了类似于线程的API,用于生成派生和处理IPC(包括同步)。
或通过subprocess.Popen
生成一个单独的子进程。如果分叉对您的资源太重(例如,通过复制父进程占用内存),请打开。
不幸的是,我没有其他办法。
通常,我认为您想在单独的线程中运行long_running_function
,并使其偶尔向主线程报告其信息。
这篇文章在wxpython程序中给出了类似的示例。
假设您正在wxpython之外执行此操作,则应该可以将thread.wx.CallAfter和wx.Publisher替换为threading.Thread和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
之前,您是否知道停止条件? 如果是这样,您可以将其作为参数传递并检查是否在内部满足。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.