embedding python module error

﹥>﹥吖頭↗ 提交于 2019-12-11 11:22:05

问题


So i have a c to python wrapper that takes input strings and pass them to a python function. the error im getting is that the python API is not recognizing my python file...

PyObject *pName, *pModule, *pFunc;
QString pyFile="Test.py";
Py_Initialize();
pName = PyUnicode_FromString(pyFile.toAscii().data());
pModule = PyImport_Import(pName);

error is "ImportError: No module named Test.py" This is when i have my Test.py in the same directory as my project

when i placed my Test.py up one level in my directory tree, another error came up error is "Import by filename is not supported"

so i guess absolute paths dont work? but in the first case in my example, i clearly placed my Test.py in the same directory as my project, why am i getting the error? python code is:

import sys
import os

def printFileClass(fileName, className):
    print ("The OMC CORBA File name is ", fileName,"\n")
    print ("The selected Modelica Class is ", className)
    return ("Done operations")


def main():
    print ("Hello! Here is testing script's main \n")



if __name__=='__main__':
main()

回答1:


The PYTHONPATH environment variable can be used to fix your problem.

In your code, you can do this somewhere before Py_Initialize():

setenv("PYTHONPATH", ".", 0); // #include <stdlib.h> to get the prototype

The third parameter, 0, means overwrite - it's zero so you can also pass PYTHONPATH from the shell. If you want to always use a path that you coded, you can set that to 1.

I'm not sure this doesn't expose you to other problems, but for a simple test it works.

Also, don't include the .py extension in the module name you pass to PyImport_Import.

I tested this on a Linux system.




回答2:


It's true in the first case there is no module named "Test.py". Your module, in the file "Test.py", is named "Test". Try importing that. "Test.py" would be the "py" submodule in a package named "Test."



来源:https://stackoverflow.com/questions/8494859/embedding-python-module-error

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