我正在尝试打印cmd ping google.com 的结果,该结果应该总共输出9行然后停止。
Pinging google.com [216.58.208.46] with 32 bytes of data:
Reply from 216.58.208.46: bytes=32 time=27ms TTL=55
Reply from 216.58.208.46: bytes=32 time=27ms TTL=55
Reply from 216.58.208.46: bytes=32 time=27ms TTL=55
Reply from 216.58.208.46: bytes=32 time=28ms TTL=55
Ping statistics for 216.58.208.46:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 27ms, Maximum = 28ms, Average = 27ms
在我的脚本下面运行
import subprocess
from subprocess import Popen, PIPE
proc = subprocess.Popen(['ping','www.google.com'],stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if line != '':
print("line:", line)
else:
break
我看到了动态打印的cmd结果行,但是在打印完最后一行之后,我的循环会永远进行打印,如下所示
line: b'Pinging www.google.com [216.58.208.36] with 32 bytes of data:\r\n'
line: b'Reply from 216.58.208.36: bytes=32 time=27ms TTL=56\r\n'
line: b'Reply from 216.58.208.36: bytes=32 time=26ms TTL=56\r\n'
line: b'Reply from 216.58.208.36: bytes=32 time=27ms TTL=56\r\n'
line: b'Reply from 216.58.208.36: bytes=32 time=26ms TTL=56\r\n'
line: b'\r\n'
line: b'Ping statistics for 216.58.208.36:\r\n'
line: b' Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),\r\n'
line: b'Approximate round trip times in milli-seconds:\r\n'
line: b' Minimum = 26ms, Maximum = 27ms, Average = 26ms\r\n'
line: b''
line: b''
line: b''
line: b''
line: b''
line: b''
line: b''
line: b''
line: b''
...
我想知道我的循环是否因为这个mysteriuos b 字符而继续,但 b 字符来自行 >
修改
print("line:", line)
到
print("line:", line[1:])
返回
line: b'inging www.google.com [216.58.208.36] with 32 bytes of data:\r\n'
line: b'eply from 216.58.208.36: bytes=32 time=28ms TTL=56\r\n'
line: b'eply from 216.58.208.36: bytes=32 time=29ms TTL=56\r\n'
line: b'eply from 216.58.208.36: bytes=32 time=27ms TTL=56\r\n'
不删除 b 字符。
我该如何解决这个问题?
答案 0 :(得分:5)
替换
if line != '':
与
if line:
输出完成后,它不会产生''
。因此,更容易检查输出是等于True
还是False
。
这在Python中很好用,因为空字符串,列表,元组,字典等,以及数字0
和值None
,都等于False
用于以上方式。
关于b
字符,表示您接收的是字节字符串,而不是普通字符串。您无法使用切片删除b
,方法是使用切片从列表中删除[]
括号。
要摆脱b,你需要decode
你的字符串。
答案 1 :(得分:0)
当您使用print()
并且输出以b
开头时,我假设您使用的是Python 3.x.在Python 3.x中,字符串由unicode字符组成,而bytes
和bytearray
由字节组成(8位)。最初的b
只是说line
实际上是bytes
个对象。
您的测试应为if str(line) != '':
或if line != b'':
,因为'' == b''
会返回False
,因为它们是不同类别的对象。
答案 2 :(得分:0)
因为这是Python,所以这个循环可以做你想要的并且更具可读性:
for line in proc.stdout:
print(line)