限制嵌入式Python的执行时间 [英] Limiting execution time of embedded Python

查看:151
本文介绍了限制嵌入式Python的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将Python解释器嵌入C或C ++程序中,如此示例,是否有任何方法可以限制解释器运行的时间?有什么方法可以阻止Python代码进入无限循环,从而阻止PyObject_CallObject(或等效代码)返回?

If I embed the Python interpreter in a C or C++ program, as in this example, is there any way to limit how long the interpreter runs for? Is there anything to stop the Python code from entering an infinite loop and thus preventing PyObject_CallObject (or equivalent) from ever returning?

类似地,如果Python代码创建了一个新线程,是否有什么方法可以阻止该线程进入无限循环并永远运行?

Similarly, if the Python code creates a new thread, is there anything to stop this thread from entering an infinite loop and running forever?

推荐答案

您可以在

As you can see in the docs, PyObject_CallObject has no mechanism for limiting how long the function runs. There is also no Python C API function that I am aware of that allows you to pause or kill a thread used by the interpreter.

因此,我们必须在停止线程运行方面更具创造力.我可以想到3种方法(从最安全/最干净到最危险...

We therefore have to be a little more creative in how we stop a thread running. I can think of 3 ways you could do it (from safest/cleanest to most dangerous...

这里的想法是,可以长时间运行的Python函数只是使用C API来查看是否应该关闭它,而直接在主应用程序内部调用另一个函数.一个简单的正确/错误结果将使您能够优雅地终止.

The idea here is that your Python function which could run for a long time simply calls another function inside your main application, using the C API to see if it should shut down. A simple True/False result would allow you to terminate gracefully.

这是最安全的解决方案,但要求您更改Python代码.

This is the safest solution, but requires that you alter your Python code.

由于您嵌入了解释器,因此您已经在使用C API,因此可以使用 PyThreadState_SetAsyncExc 强制在有问题的线程中引发异常.您可以在此处找到使用此API的示例.虽然是Python代码,但相同的功能将在您的主应用程序中起作用.

Since you are embedding the Interpreter, you are already using the C API and so could use PyThreadState_SetAsyncExc to force an exception to be raised in the offending thread. You can find an example that uses this API here. While it is Python code, the same function will work from your main application.

此解决方案的安全性稍差一些,因为它要求代码不捕获异常并在以后保持可用状态.

This solution is a little less safe as it requires the code not to catch the Exception and to remain in a usable state afterwards.

由于它本质上是不安全的,因此我不打算讨论它.请参阅是否有任何方法可以杀死Python中的线程? 关于原因的一些解释.

I'm not going to go into this one as it is inherently unsafe. See Is there any way to kill a Thread in Python? for some explanations of why.

这篇关于限制嵌入式Python的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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