Question

After much hair loss, I'm looking for help.

I'm embedding Python 3.3 into a simple app. One unusual aspect is Python isn't on the path, but it all seems to load OK. But for some reason, nothing can be executed.

Below is a small example program that shows the error:

EDIT: I know the reference counting is horrible -- this is just a simple example.

SetDllDirectory(L"D:\\dev\\python\\python33"); //so Python33.dll can be delay-loaded since not in the path

Py_Initialize();
PyObject* pGlobals = PyDict_New();
if (PyDict_GetItemString(pGlobals, "__builtins__") == NULL) 
{
    PyObject* pMod = PyImport_ImportModule("builtins"); <-- always succeeds
    if(NULL != pMod)
        PyDict_SetItemString(pGlobals, "__builtins__", pMod);
}

PyObject* pResult = PyRun_String("import sys", 0, pGlobals, pGlobals); <-- always fails

if (PyErr_Occurred()) 
{
    //PyErr_Fetch returns:
    //<class 'SyntaxError'>  
    //('invalid syntax', ('<string>', 1, 6, 'import sys'))
}

I have tried a variety of ways to import and define builtins, including various attempts shown below:

PyObject* pMod = PyImport_ImportModule("builtins");
PyDict_SetItemString(pGlobals, "builtins", pMod);
PyDict_SetItemString(pGlobals, "__builtins__", pMod);

PyDict_SetItemString(pGlobals, "__builtins__", PyEval_GetBuiltins());
PyDict_SetItemString(pGlobals, "builtins", PyEval_GetBuiltins());

None of them work -- the error is identical with each.

What am I doing wrong? Is it path related? Something about builtins that I'm doing wrong?

Était-ce utile?

La solution

Try it with the start symbol set to Py_file_input and use PyEval_GetBuiltins.

Edit: the correct dict key to set is "__builtins__".

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top