子进程标准输出的逐行处理的非终止循环

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

在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''  
python subprocess
2个回答
1
投票

在创建Popen对象时,您将获得stdout的字节流。

这在documentation中有解释

如果指定了encodingerrors参数或者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

0
投票

那是因为你正在将苹果与梨进行比较。

''b''不同

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