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

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

本文介绍了如何在C中加载自定义python模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我只是尝试获取在python文档中给出,用于在C语言中嵌入python模块才能正常工作。我的问题是我不知道将python脚本放在哪里。我的最终目标是要通过执行 PyImport_Import(将完整的python程序包(带有 __ init __。py 和各种模块的文件夹)加载到C中。 ..)。但是现在,请让我知道将显示的脚本(文件名,路径等)放在哪里,以便运行给定的C程序。

I am , as of now, simply trying to get this example given in the python docs for embedding a python module in C to work. My problem is I can't figure out where to put the python script. My ultimate goal is to have a full python package (folder with a __init__.py and various modules) to be loadable in C by executing PyImport_Import(...). But for now, please just let me know where to put the script shown (filename, path, etc) so that the C program given will run.

编辑

我应该指出我尝试过的内容。我尝试将 multiply.py 文件放在本地目录中,并将其放在名为 multiply 的子目录中在 __ init __。py 文件中。在所有这些情况下,我都会收到 ImportError:没有名为乘法的模块

I should point out what I've tried. I have tried putting a multiply.py file in the local directory, as well as putting it in a subdirectory called multiply in an __init__.py file. In all of these cases, I get ImportError: No module named multiply

推荐答案

我认为它应该在同一目录中,或者在 sys.path 中,因为它按名称加载模块,这应该可以工作:

I think it should be in the same directory or in sys.path as it loads a module by name, this should work:

./call multiply multiply 5 6

更新:如果我将当前目录显式添加到 sys.path ,它将起作用:

Update: if I add the current directory explicitly to sys.path it works:

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 相反,它可以工作:

Update: I've asked a relevant question and it seems that if you just add PySys_SetArgv instead it works:

Py_Initialize();
PySys_SetArgv(argc, argv);

此处提及原因:

这就是问题所在您也可以在那里查看答案:

And this is the question you can check the answers there too:

这篇关于如何在C中加载自定义python模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 14:56