简体   繁体   中英

Python script import from PATH in C++

I'm trying to run a Python script in a C++ program using Python.h . Because this C++ program can be installed ( make install ) in /usr/bin , it needs to be able to find the Python script both in its own directory (in case it was not installed) or in one of the PATH environment variable's directories.

I have tried doing :

PyObject *pName = PyString_FromString(scriptName); // scriptName is "file.py" as a char*
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyObject *pModule = PyImport_Import(name); // not working because absolute path only
                                           //since Python 2.7 ?

and

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append(\".\")");
PyObject *pModule = PyImport_ImportModuleEx(scriptName, NULL, NULL, NULL);

But both leave me with pModule == NULL after this call but work if I run the C++ module from its own directory.

Thanks a lot for your help

"." works as a path to your python scripts only if your C++ python script's root directory is the current working directory of your process.

If your program was started from somewhere else (either via PATH or by /path/to/a/program) then the only reliable way to find your scripts is to use use your argv[0] param from main .

Once you find the correct path, there are two ways to use it:

  1. pass it to sys.path.append
  2. switch the working directory there using chdir (from unistd.h), and then you can pass "." to sys.path.append . The chdir will affect the whole process, but pros is that you can do it directly in main .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM