简体   繁体   English

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

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

I am making a Windows GUI app in C++ in Microsoft Visual Studio 2010. I want to include a Python debug console that can be opened up through the app. 我正在用Microsoft Visual Studio 2010中的C ++开发Windows GUI应用程序。我想包括一个可以通过该应用程序打开的Python调试控制台。 I have followed this answer to connect the C++ standard I/O to the console, but when I then embed Python, Python does not seem to be able to access the console through its standard I/O: 我已经按照以下答案将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, world\n"); // works
PyRun_SimpleString("print \"hello, world\""); // does not work

I tried patching this up with the following: 我尝试使用以下方法对此进行修补:

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;

But not only do the lines marked with an asterisk (*) above cause a runtime error (the error message is nothing more than "Microsoft Visual Studio C Runtime Library has detected a fatal error in [APP_NAME].exe."), but Python's standard input still does not work, even though the input block above runs without errors. 但是,上面标有星号(*)的行不仅会导致运行时错误(错误消息无非是“ Microsoft Visual Studio C运行时库已在[APP_NAME] .exe中检测到致命错误”。),而且是Python即使上面的输入块没有错误运行,标准输入仍然不起作用。

Your program needs to use the same Microsoft C runtime DLL as was used for the version of Python you're trying to embed. 您的程序需要使用与要嵌入的Python版本相同的Microsoft C运行时DLL。 Python 2.7 is compiled with Visual Studio 2008 and uses MSVCRT90.DLL while you're using Visual Studio 2010 and MSVCRT100.DLL . Python 2.7版编译与Visual Studio 2008,并使用MSVCRT90.DLL ,而你正在使用Visual Studio 2010和MSVCRT100.DLL Each DLL has it's own stdin , stdout and stderr , that's why your create_console function has no effect. 每个DLL都有自己的stdinstdoutstderr ,这就是为什么create_console函数无效的原因。 The two DLLs also have different FILE * stream internal layouts, that's why it crashes when you pass a FILE * stream created using MSVCRT100.DLL to Python. 这两个DLL也具有不同的FILE *流内部布局,这就是当您将使用MSVCRT100.DLL创建的FILE *流传MSVCRT100.DLL Python时崩溃的原因。 It ends up trying to use it with MSVCRT90.DLL . 最终尝试与MSVCRT90.DLL一起使用它。

Basically to solve this problem you need to compile your application with Visual Studio 2008. 基本上要解决此问题,您需要使用Visual Studio 2008编译应用程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM