记录QT调用耗时的python脚本,不能实时获取python脚本日志问题

2021年10月22更新:

更好的调用python脚本获取实时日志的方式是在python中添加-u 参数(脚本中也不用在脚本中添加sys.stdout.flush()):

像这样:

    QString cmd3 = "D:/gmy/work/svnwork/rep/tensortool/debug/python_env/python.exe -u C:/temp/test.py";

python  -u 参数后会强制其标准输出也同标准错误一样不通过缓存直接打印到屏幕。

问题代码:

    QString cmd3 = "D:/gmy/work/svnwork/rep/tensortool/debug/python_env/python.exe C:/temp/test.py";
    QProcess test;
    test.start(cmd3);
    test.waitForStarted();
    while (test.state() == QProcess::ProcessState::Running) {
        if(test.waitForReadyRead(10)){
            qDebug() << test.readAllStandardError();
            qDebug() << test.readAllStandardOutput();
        }
    }
    qDebug() << "结束。。。";
    test.waitForFinished();

test.py测试耗时脚本:

import time
for index in range(4): print("hello world!"); time.sleep(1);

运行程序,理想情况是执行test.py脚本时,每隔1秒,打印一次hello word!

hello world! //1秒

hello world! //2秒

hello world! //3秒

hello world! //4秒

但实际是执行test.py脚本后,等待4秒,返回所有结果:

hello world! \r\n hello world! \r\n hello world! \r\n hello world! \r\n //4秒

原因是python在调用print后不会立即把打印的内容输出到标准输出中,是先把要打印内容放到缓冲区,等缓冲区满或调用sys.stdout.flush() 刷新时,才会把打印内容输出到标准输出中。

所以修改test.py脚本:

import time
import sys
for index in range(4):
    print("hello world!");
    time.sleep(1);
    sys.stdout.flush()

重新执行程序,输出:

hello world! //1秒

hello world! //2秒

hello world! //3秒

hello world! //4秒

原文地址:https://www.cnblogs.com/GengMingYan/p/15162032.html