规范嵌入式交互式Python解释器示例?
我想在我的C/C++应用程序中创建一个嵌入式Python解释器。理想情况下,此解释器的行为与真正的Python解释器完全相同,但在处理每一行输入后都会让步。标准Python模块规范嵌入式交互式Python解释器示例?,python,c,Python,C,我想在我的C/C++应用程序中创建一个嵌入式Python解释器。理想情况下,此解释器的行为与真正的Python解释器完全相同,但在处理每一行输入后都会让步。标准Python模块code从外部看与我想要的完全一样,只是它是用Python编写的。例如: >>> import code >>> code.interact() Python 2.7.1 (r271:86832, Jan 3 2011, 15:34:27) [GCC 4.0.1 (Apple Inc
code
从外部看与我想要的完全一样,只是它是用Python编写的。例如:
>>> import code
>>> code.interact()
Python 2.7.1 (r271:86832, Jan 3 2011, 15:34:27)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
code
的核心功能是接受可能不完整的用户输入,并显示语法错误(案例1)、等待更多输入(案例2)或执行用户输入(案例3)
Python源代码树Demo/embed/Demo.c
中的示例是外壳,但不是我想要的,因为该示例只处理完整的语句。我在这里包括部分内容供参考:
/* Example of embedding Python in another program */
#include "Python.h"
main(int argc, char **argv)
{
/* Initialize the Python interpreter. Required. */
Py_Initialize();
[snip]
/* Execute some Python statements (in module __main__) */
PyRun_SimpleString("import sys\n");
[snip]
/* Exit, cleaning up the interpreter */
Py_Exit(0);
}
我要找的是处理不完整块、堆栈跟踪等的C代码,也就是真正Python解释器的所有行为。提前谢谢。看一看。它是C++中Python的一个奇妙的集成,反之亦然。
但无论如何,您都可以使用C API。该函数在C++应用程序中提供交互式控制台。 BooST.Python是一个很棒的库,但它没有嵌入的交互式解释器。在
boost/python/exec.hpp
中,有用于评估python代码、eval
、exec
和exec\u文件的函数,但这些函数都不是用于交互使用的。是的,但是boost.python并不是C API的100%替代品。在您的情况下,请使用PyRun_InteractiveLoopFlags()函数来访问交互式控制台。Raphael,请将您的评论提升为响应?我现在明白了,还有PyRun_InteractiveOneFlags,一次进行一个语句。它缺少打印错误代码,但这可能在其他地方可用。
/* Example of embedding Python in another program */
#include "Python.h"
main(int argc, char **argv)
{
/* Initialize the Python interpreter. Required. */
Py_Initialize();
[snip]
/* Execute some Python statements (in module __main__) */
PyRun_SimpleString("import sys\n");
[snip]
/* Exit, cleaning up the interpreter */
Py_Exit(0);
}