簡體   English   中英

為什么以下循環不會中斷-Python?

[英]Why does the following loop not break - Python?

我正在嘗試打印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字符。

我怎樣才能解決這個問題?

更換

if line != '':

if line:

輸出完成后,不會產生'' 因此,更容易檢查輸出是否等於TrueFalse

在Python中,它可以很好地用作空字符串,列表,元組,字典等,以及數字0和值None ,以上述方式使用時都等於False

關於b字符,表示您收到的是字節字符串,而不是普通字符串。 您無法像使用切片一樣從列表中刪除[]括號一樣使用切片來刪除b

要擺脫b,您需要decode字符串進行decode

當您使用print()且輸出以b開頭時,我假設您使用的是Python3.x。 在Python 3.x中,字符串由unichar char組成,而bytesbytearray由字節(8位)組成。 最初的b僅表示該line實際上是一個bytes對象。

然后您的測試應該是if str(line) != '':還是if line != b'': '' == b''因為'' == b''返回False因為它們是不同類的對象。

由於這是Python,因此此循環可以滿足您的需求,並且更具可讀性:

for line in proc.stdout:
    print(line)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM