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

Jos*_*lin 13 c++ python console stdin stdout

我本质上是在尝试编写一个带有输入和输出的控制台接口,用于嵌入式python脚本.按照这里的说明,我能够捕获标准输出:

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();
Run Code Online (Sandbox Code Playgroud)

这里的问题是,我只收到了标准输出的脚本运行完毕后,而理想的控制台stdoutstring将更新为Python脚本更新它.有没有办法做到这一点?

另外,我将如何捕获stdin?

如果它有帮助,我正在使用接受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();
Run Code Online (Sandbox Code Playgroud)

斯坦丁仍然遇到麻烦......

Dav*_*ave 1

要处理 Python 中的所有可用输入,我建议使用fileinput模块。

如果您想将输入作为逐行命令处理(例如在交互式解释器中),您可能会发现 python 函数raw_input很有用。

要使用类似的帮助程序类(例如上面使用的帮助程序类)重定向标准输入,要重写的函数是readline,而不是read。有关详细信息(以及 raw_input),请参阅此链接。

希望这有帮助,Supertwang