5

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 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

5 Comments

PyImport_Import(...) expects a module name.
@ewok how do you run the program ?
@mux exactly as told in the docs: call multiply multiply 3 2
@mux got it! the path was the problem
@ewok yup, but python should look into the current directory for modules, I think the problem is in PyImport_Import I'll check.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.