gpt4 book ai didi

python - 为什么以下循环不会中断 - Python?

转载 作者:太空宇宙 更新时间:2023-11-04 08:58:20 25 4
gpt4 key购买 nike

我正在尝试打印 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''
...

我想知道我的循环是否因为这个神秘的 b 字符而继续,但是这个 b 字符来自哪里 line:?

修改

    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 字符。

我该如何解决这个问题?

最佳答案

替换

if line != '':

if line:

输出完成后不会产生''。因此,更容易检查输出是否等于 TrueFalse

这在 Python 中运行良好,如空字符串、列表、元组、字典等,以及数字 0 和值 None,都等于 以上述方式使用时为 False

关于 b 字符,表示您收到的是字节字符串,而不是普通字符串。您不能使用切片删除 b,就像您不能使用切片从列表中删除 [] 括号一样。

要摆脱 b 你需要解码你的字符串。

关于python - 为什么以下循环不会中断 - Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28152614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com