经典的嵌入式交互式Python解释器示例?
我想在我的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. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
code
的核心是一个函数,它可以接受用户输入(可能是不完整的),然后要么显示语法错误(情况1),要么等待更多输入(情况2),要么执行用户输入(情况3)。
try:
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
self.showsyntaxerror(filename)
return False
if code is None:
# Case 2
return True
# Case 3
self.runcode(code)
return False
在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解释器的行为。提前谢谢你。
1 个回答
2
看看这个 boost.python。它是把Python和C++结合得非常好的一个工具,反过来也可以。
不过,你也可以使用C语言的API。PyRun_InteractiveLoopFlags()这个函数可以让你在C++应用程序里使用一个交互式的控制台。