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.

Cristian Ciupitu
  • 20,270
  • 7
  • 50
  • 76
Drew
  • 71
  • 1
  • 4

2 Answers2

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.

ereOn
  • 53,676
  • 39
  • 161
  • 238
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • I'm sorry; I'm new to Python. What do you mean by ''? – Drew May 26 '10 at 23:59
  • The empty string. Which means the current path in `sys.path`. – Ignacio Vazquez-Abrams May 26 '10 at 23:59
  • 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. – Drew Jun 01 '10 at 20:55
  • Got it... Used PYTHONPATH= in the ~/.bashrc file. – Drew Jun 02 '10 at 01:22
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("."));
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Tmult
  • 11
  • 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. – Bowie Owens Jul 24 '19 at 01:26