请考虑以下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),就像预期的那样?
'import sys; sys.stdout.flush()'
,你会得到重定向的输出,但是在其他所有内容之前。 - user319799