Why doesn't PyRun_String evaluate bool literals?

I need to evaluate a Python expression from C ++. This code works:

PyObject * dict = PyDict_New(); PyObject * val = PyRun_String(expression, Py_eval_input, dict, 0); Py_DECREF(dict); 

Unfortunately, it fails if the expression "True" is from "False" (that is, val is 0, and PyErr_Occurred () returns true). What am I doing wrong? Shouldn't they evaluate Py_True and Py_False respectively?

+4
source share
1 answer
 PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals); 

If you want True and False, they must be in the *globals dict passed to the interpreter. You may be able to fix this by calling PyEval_GetBuiltins .

From Python 2.6 source code:

 if (PyDict_GetItemString(globals, "__builtins__") == NULL) { if (PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins()) != 0) return NULL; } 

If this does not work, you can try PyRun_String("import __builtin__ as __builtins__", globals, locals) before calling PyRun_String("True", ...) .

You may notice that the interactive Python interpreter always runs code in the __main__ module, which we did not bother to create here. I do not know if you need the __main__ module, except that there are many scripts containing if __name__ == "__main__" .

+4
source

All Articles