Python子进程readline可能在stdout提要之前

2024-05-12 23:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个GUI,它运行一个子进程,并根据进程的标准输出更新进度条。我希望这个进度条尽可能接近实时更新。以下是我当前拥有的Qthread类:

class runProgThread(QThread):
    """Using python 3.7 and pyqt5."""
    runProg = pyqtSignal(int)

    def __init__(self, parent):
        super(runProgThread, self).__init__(parent)

    def start(self, exePath):
        """When the thread is called, pass the path of the exe file into
        the class so I can access in during run."""
        self.exePath = exePath
        return super(runProgThread, self).start()

    def stop(self):
        """Just used so I can kill the process early from the main class
        with a button."""
        self.simProcess.kill()
        self.simProcess.wait()

    def run(self):
        """Each time the subprocess kicks out a line that has 'Time = ' in
        it, I add another point to the progress bar. It works fine so I
        won't go into more detail there."""
        zSteps = 0
        self.runProg.emit(0)
        self.simProcess = subprocess.Popen(self.exePath, stdout=subprocess.PIPE,
                                           bufize=1, text=True)
        while True:
            line = self.simProcess.stdout.readline()
            if (not line):
                break
            elif ('Time = ' in line):
                zSteps += 1
                self.runProg.emit(zSteps)
                time.sleep(1e-3)

它工作正常,只是进度条以非常一致的间隔挂起。我怀疑它与精确的行数有关,因为当zSteps达到214448690933的值时它会暂停。。。即使运行子流程的不同变体

我的猜测是,我可能是读线速度比他们出现,然后当它试图读一行,但什么都没有,它挂起。 我试过用缓冲器,但没什么变化

我知道我可以玩睡眠量,但我真的不想玩,因为我想在多台机器上运行这个,子进程的速度是不同的每台机器。时间是至关重要的,所以我希望进度条是尽可能接近实时饲料。我要运行1000次,所以如果我比我需要的时间长1-2秒,那么整个脚本就要长1000-2000秒

有人能证实我的怀疑是否正确吗?如果有一个解决方案不涉及优化睡眠时间

谢谢


Tags: the进度条inselfso进程defline