如何在不等待的情况下读取管道的缓冲区。子进程正在执行Swift脚本。如果它是一个python脚本,那么有一个python的标志使管道不缓冲(-u(。有其他解决方法吗?
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))
我解决了它。更改了行(添加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