如何将嵌入式 Python 连接到 Windows GUI 应用程序中控制台的 I/O?

How can I connect embedded Python to the console's I/O in a Windows GUI app?

本文关键字:控制台 应用程序 GUI 嵌入式 Python 连接 Windows      更新时间:2023-10-16

我正在Microsoft Visual Studio 2010中用C++制作一个Windows GUI应用程序。我想包括一个可以通过应用程序打开的Python调试控制台。我按照这个答案将C++标准I/O连接到控制台,但当我嵌入Python时,Python似乎无法通过其标准I/O访问控制台:

create_console(); // essentially the function in the answer I linked to above
Py_Initialize(); // initialize Python
printf("hello, worldn"); // works
PyRun_SimpleString("print "hello, world""); // does not work

我试着用以下方法修补它:

PyObject *py_stdin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
PySys_SetObject("stdin", py_stdin);
Py_DECREF(py_stdin); py_stdin = NULL;
PyObject *py_stdout = PyFile_FromFile(stdout, "<stdout>", "w", NULL); // *
PySys_SetObject("stdout", py_stdout);
Py_DECREF(py_stdout); py_stdout = NULL;
PyObject *py_stderr = PyFile_FromFile(stderr, "<stderr>", "w", NULL); // *
PySys_SetObject("stderr", py_stderr);
Py_DECREF(py_stderr); py_stderr = NULL;

但是,上面用星号(*(标记的行不仅会导致运行时错误(错误消息无非是"Microsoft Visual Studio C runtime Library在[APP_NAME].exe中检测到致命错误"(,而且Python的标准输入仍然无法工作,即使上面的输入块运行时没有错误。

您的程序需要使用与您试图嵌入的Python版本相同的Microsoft C运行时DLL。Python 2.7是使用Visual Studio 2008编译的,在使用Visual Studio 2010和MSVCRT100.DLL时使用MSVCRT90.DLL。每个DLL都有自己的stdinstdoutstderr,这就是为什么create_console函数没有效果的原因。这两个DLL也有不同的FILE *流内部布局,这就是为什么当您将使用MSVCRT100.DLL创建的FILE *流传递给Python时,它会崩溃。它最终尝试将其与MSVCRT90.DLL一起使用。

基本上要解决这个问题,您需要使用Visual Studio 2008编译应用程序。