gpt4 book ai didi

python ,C : redirected stdout fires [Errno 9]

转载 作者:可可西里 更新时间:2023-11-01 10:30:32 24 4
gpt4 key购买 nike

我尝试记录用 Python 和 C 编写的程序的所有输出。但是,从 Python 打印会导致 IOError: [Errno 9] Bad file descriptor

请问有人知道问题出在哪里以及如何解决吗?

PS:它在 Windows XP、Python 2.6 和 MinGW GCC 上

#include <windows.h>
#include <fcntl.h>
#include "Python.h"

int main()
{
int fds[2];
_pipe(fds, 1024, O_BINARY);
_dup2(fds[1], 1);
setvbuf(stdout, NULL, _IONBF, 0);

/* alternative version: */
// HANDLE hReadPipe, hWritePipe;
// int fd;
// DWORD nr;
// CreatePipe(&hReadPipe, &hWritePipe, NULL, 0);
// fd = _open_osfhandle((intptr_t)hWritePipe, _O_BINARY);
// _dup2(fd, 1);
// setvbuf(stdout, NULL, _IONBF, 0);

write(1, "write\n", 6);
printf("printf\n");
Py_Initialize();
PyRun_SimpleString("print 'print'"); // this breaks
Py_Finalize();

char buffer[1024];
fprintf(stderr, "buffer size: %d\n", read(fds[0], buffer, 1024)); // should always be more than 0

/* alternative version: */
// CloseHandle(hWritePipe);
// char buffer[1024];
// ReadFile(hReadPipe, buffer, 1024, &nr, NULL);
// fprintf(stderr, "buffer size: %d\n", nr); // should always be more than 0
}

最佳答案

我认为这可能与不同的 C 运行时有关。我知道你不能在不同的 C 运行时之间传递文件描述符 - Python 是用 MSVC 构建的(你需要检查哪个版本) - 所以你可以尝试让 MinGW 针对相同的 C 运行时构建 - 我认为有一些选择这在 MinGW 中类似于 -lmsvcrt80(或任何合适的版本),但出于许可原因,他们无法分发这些库,因此您必须在您的系统上找到它们。抱歉,我现在没有更多详细信息,但希望这是谷歌搜索的一个开始。

一个更简单的方法是在 Python 中完成这一切......只需创建一个公开 write 和可能的 flush 方法的类并将其分配给 sys.标准输出。例如,对于一个文件,您可以只传递一个打开的文件对象——为您的管道做类似的事情可能很简单。然后只需导入它和 sys 并在 PyRun_SimpleString 中设置 sys.stdout。

关于 python ,C : redirected stdout fires [Errno 9],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1749762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com