You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++调用Python程序重定向输出时内容乱序问题求助

输出重定向时C++与Python交互的输出乱序问题解决

我用VS2019编写了如下C++程序,用于调用Python脚本:

#include <stdio.h>
#include <Python.h>

void main(int argc, char *argv[])
{
    printf( "- before\n" );

    FILE* file;
    Py_SetPath( L"c:\\Python37\\Lib" );
    Py_Initialize();
    file = fopen( "abc.py", "r" );
    PyRun_SimpleFile( file, "abc.py" );
    Py_Finalize();

    printf( "- after\n" );

    return;
}

被调用的Python3.10脚本abc.py内容如下:

print( "hi" );

现象对比

  • 在Win11的cmd中直接运行main.exe时,输出顺序正常:
- before
hi
- after
  • 但将输出重定向到文件(main.exe > out.txt)或通过管道传输给tee时,输出顺序乱序:
hi
- before
- after

在实际复杂项目中,C++与Python代码交替执行时,Python输出会在脚本终止后才打印,且仅在重定向输出时出现此问题。

尝试的临时解决方法

按照@retired-ninja的建议添加setbuf( stdout, NULL );后,简单示例的问题得到解决,但复杂项目中无效。

最终有效解决方案

通过在Python脚本中添加标准输出的自动刷新配置,彻底解决了问题:

import sys
sys.stdout.reconfigure(line_buffering=True)

内容的提问来源于stack exchange,提问作者Zohar Levi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:35:20