问题描述
我已经为此苦苦挣扎了一段时间.我已经设法编写了一个可以捕获 .py 文件的 stdout 的代码,但是当我使用从 pyinstaller 生成的可执行文件运行完全相同的代码时(不管它是否窗口化)readyreadstandardoutput 信号永远不会出现.
i've been struggling with this for quite a while. i've managed to write a code that can capture stdout of .py files, however when i run the exact same code with executable generated from pyinstaller (doesn't matter whether it's windowed or not) the readyreadstandardoutput signal doesn't ever come up.
根据我的测试,只有在应用程序崩溃时才会发出任何信号,但是我需要 gui 和可执行文件之间的实时通信.
from my tests it occurs that any signal at all is emitted only when the app crashes, however i need a live communication between the gui and the executable.
这是我的参考代码:
def start_process(self, program, args=none): if args is none: args = [] process = qtcore.qprocess(self) process.readyreadstandardoutput.connect(partial(self.onreadyreadstandardoutput, self.number_process_running)) process.start(program)
以及我将信号连接到的方法:
and the method that i've connected the signal to:
def onreadyreadstandardoutput(self, i): print("called") process = self.sender() self.results[i] = process.readallstandardoutput() self.resultschanged.emit(self.results)
我正在使用 windows 机器
i'm working on a windows machine
最小的可重现示例
我们来写一个小脚本
import time if __name__ == "__main__": num = 0 while true: num = num 1 print(num) time.sleep(3)
让我们暂时离开 pyqt 进程并使用更简单的 popen.如果我们在 popen 中运行脚本,stdout 将被重定向到调用进程.
let's leave the pyqt processes for now and use simpler popen. if we run the script in popen, the stdout will be redirected to the calling process.
if __name__ == '__main__': p = popen([r'python', 'test.py'], stdin=pipe, stdout=pipe, stderr=pipe) while p.poll() is none: out = p.stdout.readline() print(out)
但是,如果我们使用第一个脚本并通过 pyinstaller 单个可执行文件生成器,popen 将不再捕获任何输出,它只会冻结
however, if we take the first script and put through pyinstaller single executable generator, the popen won't capture any output no more, it will just freeze
import os import sys import pyinstaller.__main__ file_location = os.path.dirname(os.path.realpath(__file__)) if sys.platform == "win32": pyinstaller.__main__.run([ '--name=%s' % 'test', '--onefile', '--noconsole', '--distpath=%s' % os.path.join(file_location, 'dist'), '--workpath=%s' % os.path.join(file_location, 'build'), '--specpath=%s' % os.path.join(file_location), os.path.join(file_location, 'test.py'), ])
所以我的问题是 - 我错过了其中的一些重要部分吗?或者也许这只是 pyinstaller 的错.
so again my question is - am i missing some important part in there? or maybe it's just pyinstaller's fault.
推荐答案
看来你在编译脚本的时候应该把print的flush设置为true,所以改成:
it seems that when you compile the script you should set the flush of the print to true, so just change it to:
import time if __name__ == "__main__": num = 0 while true: num = num 1 print(num, flush=true) time.sleep(3)