python __import__加载模块_python – PyImport_ImportModule,可以从内存加载模块吗?

以下示例显示如何从C字符串定义模块:

#include

#include

int main(int argc, char *argv[])

{

Py_Initialize();

PyRun_SimpleString("print('hello from python')");

// fake module

char *source = "__version__ = '2.0'";

char *filename = "test_module.py";

// perform module load

PyObject *builtins = PyEval_GetBuiltins();

PyObject *compile = PyDict_GetItemString(builtins, "compile");

PyObject *code = PyObject_CallFunction(compile, "sss", source, filename, "exec");

PyObject *module = PyImport_ExecCodeModule("test_module", code);

PyRun_SimpleString("import test_module; print(test_module.__version__)");

Py_Finalize();

return 0;

}

输出:

hello from python

version: 2.0

您可以在文档中阅读约import hooks.您需要使用find_module和load_module方法定义类.像下面这样的东西应该工作:

PyObject* find_module(PyObject* self, PyObject* args) {

// ... lookup args in available special modules ...

return Py_BuildValue("B", found);

}

PyObject* load_module(PyObject* self, PyObject* args) {

// ... convert args into filname, source ...

PyObject *builtins = PyEval_GetBuiltins();

PyObject *compile = PyDict_GetItemString(builtins, "compile");

PyObject *code = PyObject_CallFunction(compile, "sss", source, filename, "exec");

PyObject *module = PyImport_ExecCodeModule("test_module", code);

return Py_BuildValue("O", module);

}

static struct PyMethodDef methods[] = {

{ "find_module", find_module, METH_VARARGS, "Returns module_loader if this is an encrypted module"},

{ "load_module", load_module, METH_VARARGS, "Load an encrypted module" },

{ NULL, NULL, 0, NULL }

};

static struct PyModuleDef modDef = {

PyModuleDef_HEAD_INIT, "embedded", NULL, -1, methods,

NULL, NULL, NULL, NULL

};

static PyObject* PyInit_embedded(void)

{

return PyModule_Create(&modDef);

}

int main() {

...

PyImport_AppendInittab("embedded", &PyInit_embedded);

PyRun_SimpleString("\

import embedded, sys\n\

class Importer:\n\

def find_module(self, fullpath):\n\

return self if embedded.find_module(fullpath) else None\n\

def load_module(self, fullpath):\n\

return embedded.load_module(fullpath)\n\

sys.path_hooks.insert(0, Importer())\n\

");

...

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值