1

i know that there is similar question but my efforts to resolve this problem were not successful. I want to redirect Python interpreter I/O, but i have only succeeded to redirect stdout. I have still problem with stdin and stderr. Based on Redirect Embedded Python IO to a console created with AllocConsole i have done this:

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

and i have simple script for testing purposes:

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

When my script is executed only first print is show on console. Second and third commands are not shown at all. So, instead of output:

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

i have only

Hello

I would appreciate any help and it needs to be solved using Python C API. Thanks.

Community
  • 1
  • 1

1 Answers1

0

i have found solution by changing few things and using Python 3.x instead of 2.x. Now everything works fine if we modify script a bit in accordance to Python 3.x standard.

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