如何重新初始化嵌入式Python解释器?
我正在致力于将 Python 嵌入到我们的测试套件应用程序中。目的是使用Python运行多个测试脚本来收集数据并制作测试报告。一次测试运行的多个测试脚本可以创建可在下一个脚本中使用的全局变量和函数。
该应用程序还提供了在嵌入式解释器中导入的扩展模块,用于与应用程序交换一些数据。
但用户也可以进行多次测试运行。我不想共享这些全局变量、导入以及多个测试运行之间交换的数据。我必须确保在真实状态下重新启动才能控制测试环境并获得相同的结果。
我应该如何重新初始化解释器?
我使用了 Py_Initialize() 和 Py_Finalize(),但在第二次初始化我提供给解释器的扩展模块时,在第二次运行时出现异常。 并且文档警告不要多次使用它。
使用 子解释器 似乎与扩展模块初始化有相同的注意事项。
我怀疑我的扩展模块的初始化有问题,但我担心第三方扩展模块也会出现同样的问题。
也许可以通过在它自己的进程中启动解释器来使其工作,以确保释放所有内存。
顺便说一句,我使用的是 boost-python,这也会警告不要使用 Py_Finalize!
有什么建议吗?
谢谢
I'm working on embedding Python in our test suite application. The purpose is to use Python to run several tests scripts to collect data and make a report of tests. Multiple test scripts for one test run can create global variables and functions that can be used in the next script.
The application also provides extension modules that are imported in the embedded interpreter, and are used to exchange some data with the application.
But the user can also make multiple test runs. I don't want to share those globals, imports and the exchanged data between multiple test runs. I have to be sure I restart in a genuine state to control the test environment and get the same results.
How should I reinitialise the interpreter?
I used Py_Initialize() and Py_Finalize(), but get an exception on the second run when initialising a second time the extension modules I provide to the interpreter.
And the documentation warns against using it more than once.
Using sub-interpreters seems to have the same caveats with extension modules initialization.
I suspect that I'm doing something wrong with the initialisation of my extension modules, but I fear that the same problem happens with 3rd party extension modules.
Maybe it's possible to get it to work by launching the interpreter in it's own process, so as to be sure that all the memory is released.
By the way, I'm using boost-python for it, that also warns AGAINST using Py_Finalize!
Any suggestion?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是我发现实现我想要的效果的另一种方法,从解释器中的空白开始。
我可以控制用于执行代码的全局和本地命名空间:
然后我可以使用命名空间来执行
pyCode
中包含的代码:当我想要运行新实例时,我可以清理命名空间我的测试,通过清理字典:
根据我想要执行的级别,我可以使用 global = local
Here is another way I found to achieve what I want, start with a clean slate in the interpreter.
I can control the global and local namespaces I use to execute the code:
I can then use use the namespaces for execution of code contained in
pyCode
:I can clean the namespaces when I want to run a new instance of my test, by cleaning the dictionaries:
Depending at what level I want the execution, I can use global = local
使用code.IteractiveInterpreter怎么样?
像这样的事情应该这样做:
How about using
code.IteractiveInterpreter
?Something like this should do it:
我会编写另一个 shell 脚本,每次都使用新的 python 实例执行测试脚本序列。或者像这样用python编写
I'd write another shell script executing the sequence of test scripts with new instances of python each time. Or write it in python like