2016-07-31 20 views
0

Ich weiß, dass es ähnliche Frage, aber meine Bemühungen um dieses Problem zu lösen waren nicht erfolgreich. Ich möchte Python-Interpreter-I/O umleiten, aber ich bin nur gelungen, stdout umzuleiten. Ich habe immer noch Probleme mit stdin und stderr. Basierend auf Redirect Embedded Python IO to a console created with AllocConsole Ich habe dies getan:Redirect Embedded Python IO zu einer Konsole mit AlloConsole Win32-Anwendung erstellt

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

und ich habe einfaches Skript zu Testzwecken:

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

Wenn mein Skript nur ersten Druck ausgeführt wird, zeigt auf der Konsole. Zweiter und dritter Befehl werden überhaupt nicht angezeigt. Anstatt also Ausgabe:

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

ich habe nur

Hello 

ich Hilfe schätzen würde und es muss gelöst werden unter Verwendung von Python-C-API. Danke.

Antwort

0

Ich habe eine Lösung gefunden, indem ich einige Dinge geändert habe und Python 3.x anstelle von 2.x benutzt habe. Jetzt funktioniert alles gut, wenn wir das Skript ein wenig nach Python 3.x Standard modifizieren.

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