1

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()
2
  • I would seriously suggest not using the name "test" for any python module or script. There's a built-in module with that name and creating your own always causes problems. Try dropping the ".py" from your module name on the import. Commented Dec 13, 2011 at 19:22
  • so i tried with just Test, but it gave me the same error... =( Commented Dec 13, 2011 at 19:50

2 Answers 2

3

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.

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

1 Comment

Just going through the docs, Python.h already included stdlib.h for you.
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."

Comments

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.