我怎样才能停止从外部执行Python函数? [英] How can I stop the execution of a Python function from outside of it?

查看:498
本文介绍了我怎样才能停止从外部执行Python函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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

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

  def my_function() :
如果condition_checker.condition_met():
返回
library.long_running_function()

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



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

解决方案

您无法终止线程。或者库支持通过设计取消,在内部必须每隔一段时间检查一次条件以便在请求时中止,或者您必须等待它完成。



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



或者通过 subprocess.Popen 如果分叉对您的资源来说过于沉重(例如内存)

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


So I have this library that I use and within one of my functions I call a function from that library, which happens to take a really long time. Now, at the same time I have another thread running where I check for different conditions, what I want is that if a condition is met, I want to cancel the execution of the library function.

Right now I'm checking the conditions at the start of the function, but if the conditions happen to change while the library function is running, I don't need its results, and want to return from it.

Basically this is what I have now.

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

Is there a way to run the condition check every second or so and return from my_function when the condition is met?

I've thought about decorators, coroutines, I'm using 2.7 but if this can only be done in 3.x I'd consider switching, it's just that I can't figure out how.

解决方案

You cannot terminate a thread. Either the library supports cancellation by design, where it internally would have to check for a condition every once in a while to abort if requested, or you have to wait for it to finish.

What you can do is call the library in a subprocess rather than a thread, since processes can be terminated through signals. Python's multiprocessing module provides a threading-like API for spawning forks and handling IPC, including synchronization.

Or spawn a separate subprocess via subprocess.Popen if forking is too heavy on your resources (e.g. memory footprint through copying of the parent process).

I can't think of any other way, unfortunately.

这篇关于我怎样才能停止从外部执行Python函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆