如何让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
相关产品推荐
相关产品推荐

