在Python 3.7中,需要对下面的代码进行哪些具体更改,以便在
subprocess
完成运行后成功终止循环?
以下代码确实运行子进程并打印每一行。但问题是while true
循环永远不会终止,因为控制台会继续在每个新行上打印b''
,直到我重新启动机器。
import subprocess
proc = subprocess.Popen('python name-of-script.py',cwd="C:\\path\\to\\directory",stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if line != '':
#the real code does filtering here
print(line)
else:
break
在有意义的输出之后,终端继续打印以下内容:
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
b''
在创建Popen对象时,您将获得stdout
的字节流。
这在documentation中有解释
如果指定了
encoding
或errors
参数或者universal_newlines
参数是True
,则流是文本流,否则它是字节流。
因此,当你将line
与空字符串进行比较时,它总是不相等的,因为line
最多只能是一个空的byte
对象,b''
。
空字节对象是一个虚假值,因此用if line != ''
替换if line:
适用于空字符串和空字节对象。
如果以后你想要stdout
成为文本流,代码不会破坏:)
while True:
line = proc.stdout.readline()
if line:
#the real code does filtering here
print(line)
else:
break
那是因为你正在将苹果与梨进行比较。
''
与b''
不同