【问题标题】:Redirect Embedded Python IO to a console created with AllocConsole Win32 application将嵌入式 Python IO 重定向到使用 AllocConsole Win32 应用程序创建的控制台
【发布时间】:2016-07-31 14:12:22
【问题描述】:

我知道有类似的问题,但我解决这个问题的努力没有成功。我想重定向 Python 解释器 I/O,但我只成功地重定向了标准输出。我仍然对标准输入和标准错误有疑问。基于Redirect Embedded Python IO to a console created with AllocConsole 我已经这样做了:

PyObject* sys = PyImport_ImportModule("sys");
PyObject* pystdout = PyFile_FromString("CONOUT$", "wt");
if (-1 == PyObject_SetAttrString(sys, "stdout", pystdout)) {
    /* raise errors and wail very loud */
}
PyObject* pystdin = PyFile_FromString("CONIN$", "rb");
if (-1 == PyObject_SetAttrString(sys, "stdin", pystdin)) {
    /* raise errors and wail very loud */
}
//cout << "no error" << endl;
Py_DECREF(sys);
Py_DECREF(pystdout);
Py_DECREF(pystdin);

我有用于测试目的的简单脚本:

print 'Hello'
guess = int(raw_input('Take a guess: '))
print quess

当我的脚本被执行时,只有第一个打印显示在控制台上。第二和第三个命令根本没有显示。所以,而不是输出:

Hello
Take a guess: "my guess"
"my guess"

我只有

Hello

如果有任何帮助,我将不胜感激,它需要使用 Python C API 来解决。 谢谢。

【问题讨论】:

    标签: python redirect python-c-api python-c-extension


    【解决方案1】:

    我通过更改一些东西并使用 Python 3.x 而不是 2.x 找到了解决方案。如果我们根据 Python 3.x 标准稍微修改一下脚本,现在一切正常。

    PyObject* sys = PyImport_ImportModule("sys");
    if (sys == NULL)
    {
        /*show error*/
    }
    PyObject* io = PyImport_ImportModule("io");
    PyObject* pystdout = PyObject_CallMethod(io, "open", "ss", "CONOUT$", "w");
    if (pystdout == NULL)
    {
        /*show error*/
    }
    if (-1 == PyObject_SetAttrString(sys, "stdout", pystdout))
    {
        /*show error*/
    }
    PyObject* pystdin = PyObject_CallMethod(io, "open", "ss", "CONIN$", "r");
    if (pystdin == NULL)
    {
        /*show error*/
    }
    if (-1 == PyObject_SetAttrString(sys, "stdin", pystdin))
    {
        /*show error*/
    }
    PyObject* pystderr = PyObject_CallMethod(io, "open", "ss", "CONOUT$", "w");
    if (pystderr == NULL)
    {
        /*show error*/
    }
    if (-1 == PyObject_SetAttrString(sys, "stderr", pystderr))
    {
        /*show error*/
    }
    Py_DECREF(io);
    Py_DECREF(sys);
    Py_DECREF(pystdout);
    Py_DECREF(pystdin);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-09
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 2010-11-04
      • 1970-01-01
      • 1970-01-01
      • 2014-03-17
      相关资源
      最近更新 更多