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

如何让QProcess在子进程执行print时立即触发readyReadStandardOutput信号

解决Qt实时接收Python输出的问题

问题根源是Python默认会缓冲标准输出,只有缓冲区填满或程序终止时才会将内容输出到管道,导致Qt的readyReadStandardOutput信号无法实时触发。以下是两种可行的解决方法:

方法一:修改Python脚本强制刷新输出

在print语句中添加flush=True参数,让每次打印后立即刷新缓冲区:

from time import sleep

i = 0
while i < 10:
    print(f"test case {i}", flush=True)
    i += 1
    sleep(2)

或者导入sys模块手动刷新:

from time import sleep
import sys

i = 0
while i < 10:
    print(f"test case {i}")
    sys.stdout.flush()
    i += 1
    sleep(2)

方法二:启动Python时禁用缓冲

在Qt启动进程的命令中添加-u参数,该参数会强制Python禁用标准输出的缓冲:

m_pythonProcess.start("python.exe -u test.py");
m_pythonProcess.waitForStarted();

额外注意点

你的槽函数定义在RunTestCaseThread类中,但connect调用里的接收者是MainWindow的this指针,这会导致信号无法正确触发槽函数。需要确保connect的接收者是RunTestCaseThread的实例,或者将槽函数移到MainWindow类中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:57:33