我的嵌入式 python stdout 去了哪里?
Where does my embedded python stdout go?
考虑以下 MWE:
#include <Python.h>
#include <stdio.h>
int main(void) {
printf("Test 1\n");
Py_Initialize();
printf("Test 2\n");
PyRun_SimpleString("print('Test 3')");
printf("Test 4\n");
return 0;
}
当我编译并且 运行 这正常时,我得到了预期的输出:
$ ./test
Test 1
Test 2
Test 3
Test 4
但是当我重定向输出时,我从 python 代码中什么也得不到:
$ ./test | cat
Test 1
Test 2
Test 4
这是怎么回事?更重要的是,如何让我的 python 输出像预期的那样写入标准输出?
当stdout
指的是终端时,输出是行缓冲的,否则是块或完全缓冲的,直到块满时才会输出。
要在 stdout
指的是非终端时使输出行缓冲,请将模式设置为 setvbuf
您必须调用 Py_Finalize()
才能让 libpython
关闭其 I/O 句柄。
#include <Python.h>
#include <stdio.h>
int
main(int argc, char **argv) {
//setlinebuf(stdout);
setvbuf(stdout, NULL, _IOLBF, 0);
printf("Test 1\n");
Py_Initialize();
printf("Test 2\n");
PyRun_SimpleString("print('Test 3')");
Py_Finalize();
printf("Test 4\n");
return 0;
}
当前Python,您可以使用Py_UnbufferedStdioFlag
。
考虑以下 MWE:
#include <Python.h>
#include <stdio.h>
int main(void) {
printf("Test 1\n");
Py_Initialize();
printf("Test 2\n");
PyRun_SimpleString("print('Test 3')");
printf("Test 4\n");
return 0;
}
当我编译并且 运行 这正常时,我得到了预期的输出:
$ ./test
Test 1
Test 2
Test 3
Test 4
但是当我重定向输出时,我从 python 代码中什么也得不到:
$ ./test | cat
Test 1
Test 2
Test 4
这是怎么回事?更重要的是,如何让我的 python 输出像预期的那样写入标准输出?
当stdout
指的是终端时,输出是行缓冲的,否则是块或完全缓冲的,直到块满时才会输出。
要在 stdout
指的是非终端时使输出行缓冲,请将模式设置为 setvbuf
您必须调用 Py_Finalize()
才能让 libpython
关闭其 I/O 句柄。
#include <Python.h>
#include <stdio.h>
int
main(int argc, char **argv) {
//setlinebuf(stdout);
setvbuf(stdout, NULL, _IOLBF, 0);
printf("Test 1\n");
Py_Initialize();
printf("Test 2\n");
PyRun_SimpleString("print('Test 3')");
Py_Finalize();
printf("Test 4\n");
return 0;
}
当前Python,您可以使用Py_UnbufferedStdioFlag
。