python - 规范的嵌入式交互式 Python 解释器示例?

标签 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. 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);
}

我正在寻找的是处理不完整 block 、堆栈跟踪等的 C 代码。也就是说,真正的 Python 解释器的所有行为。提前致谢。

最佳答案

看看boost.python .这是 Python 在 C++ 中的出色集成,反之亦然。

但是您仍然可以使用 C API。 PyRun_InteractiveLoopFlags()函数在您的 C++ 应用程序中提供交互式控制台。

关于python - 规范的嵌入式交互式 Python 解释器示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4596370/

相关文章:

c - 使用双向链表排序的问题

python - 使用 Python 将 CSV 文件从目录导入到 MySql 表中

c# - 没有循环迭代器的枚举

c - 在 (Eclipse CDT) autotools 项目中添加 CFLAG(例如 -std=gnu99)的位置

python - 使用 bs4 进行网页抓取验证

c - 从c中的标准输入读取直到EOF

c - int 数组的动态内存分配

python - 根据索引矩阵对 numpy 矩阵进行排序

python:在 __init__ 方法中过早调用 super().__init__ ?

Python:从 'list' 的 {(tuples): value} 字典写入 csv 文件