加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在c中加载自定义python模块

发布时间:2020-12-16 05:02:21 所属栏目:百科 来源:网络整理
导读:到目前为止,我只是试图在 python文档中获得 this example,以便在C语言中嵌入python模块.我的问题是我无法弄清楚放置python脚本的位置.我的最终目标是通过执行PyImport_Import(…)将一个完整的python包(带有__init__.py和各种模块的文件夹)加载到C中.但是现在
到目前为止,我只是试图在 python文档中获得 this example,以便在C语言中嵌入python模块.我的问题是我无法弄清楚放置python脚本的位置.我的最终目标是通过执行PyImport_Import(…)将一个完整的python包(带有__init__.py和各种模块的文件夹)加载到C中.但是现在,请让我知道在哪里放置显示的脚本(文件名,路径等),以便运行给出的C程序.

编辑

我应该指出我尝试过的东西.我尝试将multiply.py文件放在本地目录中,并将其放在__init__.py文件中名为multiply的子目录中.在所有这些情况下,我得到ImportError:没有名为multiply的模块

解决方法

我认为它应该在同一目录或sys.path中,因为它按名称加载模块,这应该工作:
./call multiply multiply 5 6

更新:如果我将当前目录显式添加到sys.path它可以工作:

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(".")");

这打印:

./call multiply multiply 5 6
('Will compute',5,'times',6)
Result of call: 30

更新:我已经问了一个相关的问题,看起来如果你只是添加PySys_SetArgv而不是它有效:

Py_Initialize();
PySys_SetArgv(argc,argv);

这里提到的原因是:

Otherwise (that is,if argc is 0 or argv[0] doesn’t point to an
existing file name),an empty string is prepended to sys.path,which
is the same as prepending the current working directory (“.”)

这也是你可以在那里检查答案的问题:

Why does PyImport_Import fail to load a module from the current directory?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读