【问题标题】:Canonical embedded interactive Python interpreter example?规范的嵌入式交互式 Python 解释器示例?
【发布时间】:2011-01-04 17:11:05
【问题描述】:

我想在我的 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 解释器的所有行为。提前致谢。

【问题讨论】:

    标签: python c


    【解决方案1】:

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

    但无论如何您都可以使用 C API。 PyRun_InteractiveLoopFlags() 函数在您的 C++ 应用程序中提供了一个交互式控制台。

    【讨论】:

    • Boost.Python 是一个很棒的库,但它没有嵌入式交互式解释器。在boost/python/exec.hpp 中有评估Python 代码的函数evalexecexec_file,但这些都不是用于交互使用的。
    • 是的,但是 boost.python 不是 C API 的 100% 替代品。在您的情况下,使用 PyRun_InteractiveLoopF​​lags() (docs.python.org/c-api/veryhigh.html#PyRun_InteractiveLoopFlags) 函数来午餐交互式控制台。
    • Raphael,您能否将您的评论提升为回复?我现在看到还有 PyRun_InteractiveOneFlags 一次执行一个语句。它缺少错误打印代码,但可能在其他地方可用。
    猜你喜欢
    • 2013-09-08
    • 2017-05-16
    • 2015-06-29
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    相关资源
    最近更新 更多