【问题标题】:how to read subprocess pipe without buffering如何在不缓冲的情况下读取子进程管道
【发布时间】:2021-03-30 02:15:18
【问题描述】:

如何在不等待的情况下读取管道的缓冲区。子进程正在执行 Swift 脚本。如果它是一个 python 脚本,则有一个用于使管道无缓冲 (-u) 的 python 标志。还有什么办法可以解决吗?

sub_proc = subprocess.Popen(['swift', 'script2.swift'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
thr1 = threading.Thread(target=self.pipe_reader, args=[sub_proc.stdout]).start()
thr2 = threading.Thread(target=self.pipe_reader, args=[sub_proc.stderr]).start()


def pipe_reader(self, pipe):
    for line in iter(pipe.readline, b''):
        self.q.put((pipe, line))
    self.q.put((pipe, None))

【问题讨论】:

    标签: python subprocess pipe buffer


    【解决方案1】:

    我解决了。换行(添加 stdbuf -o0 作为参数)

    sub_proc = subprocess.Popen(['swift', 'script2.swift'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    

    sub_proc = subprocess.Popen(['stdbuf', '-o0','swift', 'script2.swift'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    

    有关 stdbuf 的更多信息:https://www.gnu.org/software/coreutils/manual/html_node/stdbuf-invocation.html

    【讨论】:

      猜你喜欢
      • 2021-02-21
      • 2016-02-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 2013-08-05
      • 2016-12-19
      • 2015-10-12
      相关资源
      最近更新 更多