异步将 stdout/stdin 从嵌入式 python 重定向到 C++?

2024-04-04

我本质上是想为嵌入式 python 脚本编写一个带有输入和输出的控制台界面。按照说明进行操作here http://docs.python.org/faq/extending.html#how-do-i-catch-the-output-from-pyerr-print-or-anything-that-prints-to-stdout-stderr,我能够捕获标准输出:

Py_Initialize();
PyRun_SimpleString("\
class StdoutCatcher:\n\
    def __init__(self):\n\
        self.data = ''\n\
    def write(self, stuff):\n\
        self.data = self.data + stuff\n\
import sys\n\
sys.stdout = StdoutCatcher()");

PyRun_SimpleString("some script");

PyObject *sysmodule;
PyObject *pystdout;
PyObject *pystdoutdata;    
char *string;
sysmodule = PyImport_ImportModule("sys");
pystdout = PyObject_GetAttrString(sysmodule, "stdout");
pystdoutdata = PyObject_GetAttrString(pystdout, "data");    
stdoutstring = PyString_AsString(pystdoutdata);

Py_Finalize();

问题是我只收到标准输出after脚本已完成运行,而理想情况下,对于控制台来说,stdoutstring 将随着 python 脚本的更新而更新。有没有办法做到这一点?

另外,我将如何捕获标准输入?

如果有帮助的话,我正在使用一个接受 Objective-C 的编译器。我还有可用的升压库。


我已经弄清楚了问题的标准输出部分。对于后代来说,这是有效的:

static PyObject*
redirection_stdoutredirect(PyObject *self, PyObject *args)
{
    const char *string;
    if(!PyArg_ParseTuple(args, "s", &string))
        return NULL;
    //pass string onto somewhere
    Py_INCREF(Py_None);
    return Py_None;
}

static PyMethodDef RedirectionMethods[] = {
    {"stdoutredirect", redirection_stdoutredirect, METH_VARARGS,
        "stdout redirection helper"},
    {NULL, NULL, 0, NULL}
};

//in main...
    Py_Initialize();
    Py_InitModule("redirection", RedirectionMethods);
    PyRun_SimpleString("\
import redirection\n\
import sys\n\
class StdoutCatcher:\n\
    def write(self, stuff):\n\
        redirection.stdoutredirect(stuff)\n\
sys.stdout = StdoutCatcher()");

    PyRun_SimpleString("some script");

    Py_Finalize();

标准输入仍然有问题...


要处理 Python 中的所有可用输入,我建议文件输入 http://docs.python.org/library/fileinput.html?highlight=stdin#fileinput.isstdin module.

如果您想将输入作为逐行命令处理(例如在交互式解释器中),您可能会找到 python 函数原始输入 http://docs.python.org/library/functions.html?highlight=raw_input#raw_input useful.

要使用类似的辅助类(例如上面使用的辅助类)重定向标准输入,要重写的函数是readline, not read. See 这个链接 http://www.ragestorm.net/blogs/?p=53有关更多信息(以及 raw_input)。

希望这可以帮助, 超级鼻音

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

异步将 stdout/stdin 从嵌入式 python 重定向到 C++? 的相关文章

随机推荐