我本质上是试图编写一个控制台接口输入和输出嵌入式的Python脚本。继说明here,我能捕捉到标准输出:将stdout/stdin从嵌入式python异步重定向到C++?
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();
这样做的问题是,我只收到标准输出脚本运行完毕后,而理想的控制台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();
还是有问题:标准输入...
PS:
你可以对其进行测试。感谢您的解决方案,我发现它们非常有帮助! – Dave