Question

I'm following a tutorial to call python code from a C++ program from the python docs.

Everything works just fine when trying to call the multiply example. Now if I add a line to the python source code importing a library, lets say openpyxl,

from openpyxl import load_workbook

I receive an error from python

ImportError: No module named openpyxl

I thought if I import a system library, I wouldn't have any problems, but I also get an error if I try to import datetime.

I don't have any error if I import the file from the python console. The openpyxl library is installed in my system.

So my question is: how to import python source code that needs to import packages?

EDIT: Ok, I forgot to mention something, I have not been completely honest with you guys, I'm sorry.

Trying to run the example I run into a problem: I couldn't make python found my multiply.py file, and the line PyImport_Import always return null.

My solution was to add the path in which I knew my python source was by using PySys_SetPath. The problem is that I just realized that this function doesn't append a new directory, it just overwrites the PYTHONPATH. So now python can find multiply.py, but absolutly anything else.

Of course I've deleted that line but now I have another question, why does python can't find my source if the file is just in the same directory of the C++ compiled program?

The I realized that my sys.path from my python console was a little different from the path showed in my embedded python: the first one had at the beginning of the list an empty string ''. I'm not a python expert, but when I add that line to my path I could import the multiply.py so it seems that was the reason I couldn't import modules that were located to relative to my executable was the missing of this empty path -but still don't know what it means-.

I have to thank to @paul-evans who give me the idea of adding the path to find my files.

Was it helpful?

Solution

This is what PYTHONPATH is for. You can set it as an environment variable containing a list module directories, or in the code itself something like:

import sys
sys.path.append("path/to/openpyxl/module")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top