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

一笑奈何 提交于 2019-12-03 05:38:27

To process all available input inside Python I'd recommend the fileinput module.

If you want to handle input as line-by-line commands, (such as in an interactive interpreter), you might find the python function raw_input useful.

To redirect stdin using a similar helper class such as the ones you've used above, the function to override is readline, not read. See this link for more info on that (and also raw_input).

Hope this helps, Supertwang

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()");

If you stick with the approach you outlined, inheriting your class from io.IOBase is probably a good idea.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!