Asynchronously redirect stdout/stdin from embedded python to c++?

后端 未结 3 2012
忘了有多久
忘了有多久 2021-02-07 10:04

I am essentially trying to write a console interface with input and output for an embedded python script. Following the instructions here, I was able to capture stdout:

3条回答
  •  旧时难觅i
    2021-02-07 10:38

    Easiest way I found so far to do this is as follows:

    PyObject *sys = PyImport_ImportModule("sys");
    PyObject* io_stdout = PyFile_FromFile(stdout, "stdout", "a", nullptr);
    PyObject_SetAttrString(sys, "stdout", io_stdout);
    PyObject* io_stderr = PyFile_FromFile(stderr, "stderr", "a", nullptr);
    PyObject_SetAttrString(sys, "stderr", io_stderr);
    PyObject* io_stdin = PyFile_FromFile(stdin, "stdin", "r", nullptr);
    PyObject_SetAttrString(sys, "stdin", io_stdin);
    

    you can test it with:

    # for test
    PyRun_SimpleString("print sys.stdin.readline()");
    

提交回复
热议问题