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)
斯坦丁仍然遇到麻烦......
| 归档时间: |
|
| 查看次数: |
3181 次 |
| 最近记录: |