6

I need to run Python scripts within a C-based app. I am able to import standard modules from the Python libraries i.e.:

PyRun_SimpleString("import sys")

But when I try to import a local module can

PyRun_SimpleString("import can")

returns the error message:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ImportError: No module named can

When I type the command import can in IPython, the system is able to find it.

How can I link my app with can? I've tried setting PYTHONPATH to my working directory.

2 Answers 2

9

Embedding the Python library does not add '' to sys.path like the interactive interpreter does. Use PySys_SetPath() to add the appropriate directory.

Oh hey, look what I found.

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

4 Comments

I'm sorry; I'm new to Python. What do you mean by ''?
The empty string. Which means the current path in sys.path.
I got it to work... Although I'm unsure how and am trying to replicate the results on another machine. I've tried using sys.path.append as well as manually concatenating strings representing sys.path and my desired path. It seems that I can't have both the system path and my path at the same time. Thanks for the help.
Got it... Used PYTHONPATH=<working directory> in the ~/.bashrc file.
0

I found this to work much more robustly,

PyObject *sys = PyImport_ImportModule("sys");
PyObject *path = PyObject_GetAttrString(sys, "path");
PyList_Append(path, PyUnicode_FromString("."));

1 Comment

I found this approach useful. Note that it is missing Py_DECREF calls so it will leak references. It is also missing error checking but these calls should probably always succeed.

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.