简体   繁体   English

为什么PyRun_String不评估bool文字?

[英]Why doesn't PyRun_String evaluate bool literals?

I need to evaluate a Python expression from C++. 我需要从C ++中评估一个Python表达式。 This code seems to work: 这段代码似乎有效:

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

Unfortunately, it fails horribly if expression is "True" of "False" (that is, val is 0 and PyErr_Occurred() returns true). 不幸的是,如果表达式为“False”的“True”(即val为0且PyErr_Occurred()返回true),则会失败。 What am I doing wrong? 我究竟做错了什么? Shouldn't they evaluate to Py_True and Py_False respectively? 他们不应该分别评估Py_True和Py_False吗?

PyObject* PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals);

If you want True and False they will have to be in the *globals dict passed to the interpreter. 如果你想要True和False,他们必须在传递给解释器的*globals dict中。 You might be able to fix that by calling PyEval_GetBuiltins . 您可以通过调用PyEval_GetBuiltins来解决这个PyEval_GetBuiltins

From the Python 2.6 source code: 从Python 2.6源代码:

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

If that doesn't work, you could try to PyRun_String("import __builtin__ as __builtins__", globals, locals) before calling PyRun_String("True", ...) . 如果这不起作用,你可以在调用PyRun_String("True", ...)之前尝试PyRun_String("import __builtin__ as __builtins__", globals, locals) PyRun_String("True", ...)

You might notice the Python interactive interpreter always runs code in the __main__ module which we haven't bothered to create here. 您可能会注意到Python交互式解释器始终在__main__模块中运行代码,我们在这里无需创建。 I don't know whether you need to have a __main__ module, except that there are a lot of scripts that contain if __name__ == "__main__" . 我不知道你是否需要一个__main__模块,除了有很多脚本包含if __name__ == "__main__"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM