how to load a custom python module in c

2019-04-30 05:43发布

问题:

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?



标签: python c embed