我的嵌入式Python标准输出(stdout)去哪了?

16

请考虑以下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),就像预期的那样?


有趣的是,如果你在Python脚本中添加 'import sys; sys.stdout.flush()',你会得到重定向的输出,但是在其他所有内容之前。 - user319799
2个回答

5

在当前的Python版本中,您可以使用Py_UnbufferedStdioFlag


4
当标准输出(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中,您可以调用sys.stdout.flush()。调用Py_Finalize()可能不适合他的使用情况。 - tynn
如果你不调用 Py_Finalize(),输出结果会是无序的,这是 Python 的特性。 - Nizam Mohamed
啊...当然,现在一切都显得那么明显 :) 谢谢! - A. Nilsson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接