子进程通信函数始终为空

问题描述 投票:0回答:1

我正在尝试使用自定义打印功能将子进程的输出直接打印到自定义构建的终端。这涉及到两段代码,有问题的代码在这里:

with subprocess.Popen(f"{command}", cwd=directory, stdout=subprocess.PIPE, shell=False, text=True) as translator:
   self.terminal.printGUI("Starting print")
   while True:
      output, error = translator.communicate()
      if translator.poll() is not None:
         break
      if output:
         count += 1
         self.terminal.printGUI(output.strip())

   self.terminal.printGUI("Ending print")

但是,当打印以子进程开始和结束时,translator.communicate() 始终为空。被调用的自定义打印函数在这里:

def printGUI(self, text):
   self.textbox.configure(state="normal")
   self.textbox.insert("end", text + "\n")
   #delete first line if there are more than 100 lines
   if len(self.textbox.get("1.0", "end-1c").split("\n")) > 100:
      self.textbox.delete("1.0", "2.0")
            
   self.textbox.configure(state="disabled")

此函数按预期工作,并且使用 tkInter 文本框。

当 stdout 接收文本时,应调用自定义打印函数。

程序的这一段预计是从子进程的标准输出到 tkInter 文本框的管道,为 GUI 创建终端。被调用的子进程需要很长时间,并且在终端上打印很多内容,所以我试图使 printGUI 实时打印。

python subprocess
1个回答
0
投票

如果您的子流程输出是面向行的,那么您可以利用此模式:

import subprocess
import sys

COMMAND = "Your command goes here"

with subprocess.Popen([COMMAND], stdout=subprocess.PIPE, encoding="utf-8") as p:
    while line := p.stdout.readline():
        sys.stdout.write(line)
© www.soinside.com 2019 - 2024. All rights reserved.