简体   繁体   English

运行python pyd模块的几个独立实例

[英]Running several independent instances of python pyd module

I wondering is there a solution to import one compiled from C++ source pyd module twice. 我想知道是否有一种解决方案可以两次从C ++源pyd模块导入一个编译的文件。 So to have 2 separate instances of one module with distinct values of variables defined in C? 那么一个模块有2个单独的实例,它们在C中定义了不同的变量值? Here is the example. 这是例子。 I have a simple cpp module: 我有一个简单的cpp模块:

#include <boost/python/module.hpp>
#include <boost/python/def.hpp>
int n;
void set(int i)
{
    n = i;
}
int get()
{
    return n;
}
BOOST_PYTHON_MODULE(test_ext)
{
    using namespace boost::python;
    def("set", set);
    def("get", get);
}

now I'm trying to import it twice: 现在,我尝试将其导入两次:

In [1]: import sys

In [2]: import test_ext as t1

In [3]: del sys.modules['test_ext']

In [4]: import test_ext as t2

In [5]: t1.set(1)

In [6]: t2.set(2)

In [7]: t1.x=1

In [8]: t2.x=2

In [9]: t1.x
Out[9]: 1

In [10]: t2.x
Out[10]: 2

In [11]: t1.get()
Out[11]: 2

In [12]: t2.get()
Out[12]: 2

As you can see both modules points to the same variable. 如您所见,两个模块都指向同一个变量。 If I setting it in one module it changed in another. 如果在一个模块中设置它,则在另一个模块中更改它。

Actually I have a code generated by Matlab and there are many global variables in it. 实际上,我有Matlab生成的代码,其中包含许多全局变量。 I want to find a way to run this code independently in several instances of module. 我想找到一种在模块的多个实例中独立运行此代码的方法。 By the way I'm using python 2.7 顺便说一句我正在使用python 2.7

Thanks in advance! 提前致谢!

An issue with this is that C extensions of Python are escaping Python VM sandbox (there is even note of this behaviour in Python documentation). 与此相关的问题是Python的C扩展正在逃避Python VM沙箱(在Python文档中甚至对此行为进行了记录)。

You virtually cannot expect to have more than one instance of global variable in C in one address space (eg one process). 实际上,您不能期望一个地址空间中的C中有多个全局变量实例(例如,一个进程)。 It is just not possible and it is even not anyhow connected to Python. 这是不可能的,甚至无法以任何方式连接到Python。

BTW: You can actually even 'interconnect' two Python VMs running in single process this way. 顺便说一句:实际上,您甚至可以以这种方式“互连”在单个进程中运行的两个Python VM。

So how to solve this: 那么如何解决这个问题:

  1. C-level global variables are actually a map (or dictionaries) where key is identifier of Python VM (or anything else that will fit your case). C级全局变量实际上是一个映射(或词典),其中键是Python VM的标识符(或其他适合您情况的标识符)。 Since you are in C, this is however not the easiest case. 由于您使用C语言,因此这不是最简单的情况。

  2. Encapsulate module in dedicated process space - start a subprocess. 将模块封装在专用进程空间中-启动子进程。 You will need to however resolve how to communicate with parent process if needed. 但是,如果需要,您将需要解决如何与父流程进行通信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM