how to load a custom python module in c

被刻印的时光 ゝ 提交于 2019-12-22 06:50:24

问题


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.

EDIT

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


回答1:


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

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

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

And this prints:

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

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);

The reason is mentioned here:

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 (".")

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

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



来源:https://stackoverflow.com/questions/13422206/how-to-load-a-custom-python-module-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!