【发布时间】:2009-11-09 00:07:44
【问题描述】:
我在将 Python IO 重定向到我为我的 Win32 应用程序分配的控制台时遇到了一些问题。是否有我需要重定向的特定于 Python 的流?
这或多或少是我现在正在做的事情(删除了错误检查等):
int __stdcall WinMain(/*Usual stuff here*/) {
// Create the console
AllocConsole();
SetConsoleTitle(L"My Console");
// Redirect Standard IO Streams to the new console
freopen("CONOUT$","w",stdout);
freopen("CONOUT$","w",stderr);
freopen("CONIN$","r",stdin);
// Test the console:
printf("This Works.\r\n");
cout << "So Does this" << endl;
// Python Stuff (This is where it fails)
Py_Initialize();
PyRun_SimpleString("print('I don't work.')\n");
Py_Finalize();
}
如果我作为控制台应用程序(Visual Studio 05,顺便说一句)运行相同的东西并删除 AllocConsole 调用,一切正常。有人知道我错过了什么吗?
编辑:为了澄清起见,我正在寻找一种从 C API 中执行此操作的方法。
另一个编辑:Alex 的解决方案是正确的,但对于使用 Python 3.x 的任何人,您可能会注意到新 API 中缺少 PyFile_FromString 函数。虽然它可能不是最好的选择,但我发现这在 Python 3.x 中运行良好:
PyObject* sys = PyImport_ImportModule("sys");
PyObject* io = PyImport_ImportModule("io");
PyObject* pystdout = PyObject_CallMethod(io, "open", "ss", "CONOUT$", "wt");
if (-1 == PyObject_SetAttrString(sys, "stdout", pystdout)) {
/* Announce your error to the world */
}
Py_DECREF(sys);
Py_DECREF(io);
Py_DECREF(pystdout);
【问题讨论】:
标签: python console io-redirection