嵌入python和运行多次 [英] Embedding python and running for multiple times

查看:276
本文介绍了嵌入python和运行多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用boost :: python嵌入python,这是我怎么做:

  void runCode {
Py_Initialize();
// boost :: python代码在这里和嵌入式python代码运行
Py_Finalize();
}

它第一次运行很好,但是当它再次运行时,我发生此错误:


LookupError:未知编码:utf8



$ b

解决方案

因为你没有得到一个专家回答,我提供我的学习从一个类似的问题。
Python对重新初始化支持有问题。这是不幸的,如果你需要重新启动解释器由于一些错误,或者想要运行许多独立的解释器。



一个问题有泄漏的资源和内存以上链接):


错误和警告:由
加载的动态加载的扩展模块Python不会卸载。由
Python解释器分配的少量内存可能不会被释放(如果您发现有泄漏,请报告
it)。在对象之间的循环引用中绑定的内存不是
释放。扩展模块分配的某些内存可能不会释放。
一些扩展可能无法正常工作,如果他们的初始化例程
被多次调用;如果应用程序多次调用
Py_Initialize()和Py_Finalize(),可能会发生这种情况。


不正确地支持这一点,例如可以看出在这个SO线程我认为这是你面对的问题。



看起来大多数Python应用程序都可以解决这个问题:




  • 使引擎在专用进程中运行;

  • 使用
  • .python.org / c-api / init.html#sub-interpreter- supportrel =nofollow> subinterpreters 。 / ul>

    如果第二个适用于您,请继续。


    I'm using boost::python to embed python, this is how I do it:

    void runCode(){
        Py_Initialize();
        //boost::python code goes here and embedded python code runs
        Py_Finalize();
    }
    

    it runs nicely for the first time, but when it is run again, I get this error:

    LookupError: unknown encoding: utf8

    and code does not run as expected, any help is appreciated.

    解决方案

    Since you didn't get an expert answer, I'm offering my learning from working on a similar problem. Python have issues with reinitialization support. This is unfortunate if you need to restart the interpreter due to some error, or want to run many independent interpreters.

    One issue there is leaking resources and memory (quoting from the above link):

    Bugs and caveats: Dynamically loaded extension modules loaded by Python are not unloaded. Small amounts of memory allocated by the Python interpreter may not be freed (if you find a leak, please report it). Memory tied up in circular references between objects is not freed. Some memory allocated by extension modules may not be freed. Some extensions may not work properly if their initialization routine is called more than once; this can happen if an application calls Py_Initialize() and Py_Finalize() more than once.

    Another issue is many modules don't support this properly, as can be seen for example in this SO thread. I think this is the problem you're facing.

    It seems that most Python applications work-around this problem:

    • by having the engine run in a dedicated process ;
    • by using subinterpreters which represent distinct execution states (of a common interpreter)

    If the second one works for you, go ahead with it.

    这篇关于嵌入python和运行多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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