'Import sys' succeeds in C++ embedded code, but module is not fully visible

Christian Heimes lists at cheimes.de
Wed Jan 14 03:18:37 CET 2009

Ivan Illarionov schrieb:
> Ben Sizer <kylo... at gmail.com> wrote:
>> What am I doing wrong?
> What are you trying to achieve?
> If you want to modify sys.path I suggest using Python/C API directly:
> (boilerplate removed)
> PyImport_ImportModule("sys")
> PyObject_GetAttrString(sysmod_pointer, "path")
> PyList_Insert(pathobj_pointer, 0, path_python_str)

The sys module has its own set of special functions like
PySys_GetObject. The following (untested) code should take care of error
checking and ref counting.

#include "Python.h"

addtosyspath(const char* addpath) {
    PyObject *syspath=NULL, *path=NULL;
    int result;

    if ((syspath = PySys_GetObject("path")) == NULL)
        return NULL;
    if ((path = PyString_FromString(addpath) == NULL) {
        return NULL;
    result = PyList_Insert(syspath, 0, path);
    if (result != 0)
        return NULL;


More information about the Python-list mailing list