从进程输出读取时代码被卡在循环中

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

此代码从不打印“ hello”。不知道为什么吗?

proc = subprocess.Popen(
'./lite-client -C ton-lite-client-test1.config.json -D ./ton-db-dir',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True)

line = proc.stderr.readline()
while line != "":
    print(line)
    print(len(line))
    line = proc.stderr.readline()
print("hello")

一旦打印出stderr中的所有内容,它仍然不会打印“ hello”。 stderr是有限的,它在启动时打印约20行。

有什么想法吗?

更新:stderr来自长时间运行的过程。我想与此过程进行交互,发送命令并读取输出。

更新2:我做出了可行的解决方法,如果字符串包含特定的子字符串,我添加了break

python subprocess
1个回答
4
投票

我能够通过替换来解决问题

subprocess.Popen(
    ['perl', '-e', 'for my $i (1..20) { warn "Not hello $i"; sleep 1 }'],
    ...) # no shell=True; see below

这里stderr的输出是bytes。您可以将text=True添加到关键字参数中,或更改为while line != b""

此外,您也可以轻松地get rid of the pesky shell=True.

shell=True

我可能还会在行为空时更改为import subprocess proc = subprocess.Popen( ['./lite-client', '-C', 'ton-lite-client-test1.config.json', '-D', './ton-db-dir'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) line = proc.stderr.readline() while line != "": print(line, end='') # line already has a newline print(len(line)) line = proc.stderr.readline() print("hello") ,然后更改为while True:,这样您就不会有任何重复的代码。我并没有在此进行更改,只是为了更轻松地比较我们的程序。

© www.soinside.com 2019 - 2024. All rights reserved.