从 ping return 中过滤掉不需要的数据
Filtering out unwanted data from ping return
我正在尝试 ping Google DNS 以获得互联网连接的延迟,然后将其通过 COM 端口发送到带有精美灯光和一些噱头的 arduino,因此我不必每隔几分钟在 CMD 提示符中输入 alt 选项卡。问题是下面的代码要么没有过滤掉所需的信息,要么简单明了地拒绝工作,在我对编程了解不多的情况下,它已经成为一个相当大的挑战。
import subprocess
import re
ping = subprocess.Popen(["ping", "8.8.8.8", "-n", "1"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell=True)
output = ping.communicate()
pattern = r"time= (\d+\S+)"
re.findall(pattern, output[0].decode('utf-8'))[0]
print(output)
输出为:
IndexError: list index out of range
但是如果我改变
pattern = r"time= \d+\S+)"
至
pattern = r"Average = \d+\S+)"
输出变为:
(b'\r\nPinging 8.8.8.8 with 32 bytes of data:\r\nReply from 8.8.8.8: bytes=32 time=26ms TTL=122\r\n\r\nPing statistics for 8.8.8.8:\r\n Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),\r\nApproximate round trip times in milli-seconds:\r\n Minimum = 26ms, Maximum = 26ms, Average = 26ms\r\n', b'')
它会 ping Google DNS 但不会过滤掉所需的 20 毫秒,理想情况下输出为 20 没有毫秒。
有什么想法是我的小脑袋哪里出了问题吗?谢谢:)
我想下面的内容可能对您有所帮助:
import re
m = re.search(r'time=(\d+)ms', output[0].decode('utf-8'))
if m:
print(m.group(1))
此外,您可能希望将结果转换为 int
,即
if m:
latency = int(m.group(1))
(这不会改变输出,但现在你操纵的是一个数字,而不是一个字符串)。
问题是 space 字符 (</code>) 在等号 <code>=
之前。由于您提供的字符串中有 none,您的正则表达式失败。
将您的正则表达式模式更改为 r'\btime=\s*(\d+)'
我正在尝试 ping Google DNS 以获得互联网连接的延迟,然后将其通过 COM 端口发送到带有精美灯光和一些噱头的 arduino,因此我不必每隔几分钟在 CMD 提示符中输入 alt 选项卡。问题是下面的代码要么没有过滤掉所需的信息,要么简单明了地拒绝工作,在我对编程了解不多的情况下,它已经成为一个相当大的挑战。
import subprocess
import re
ping = subprocess.Popen(["ping", "8.8.8.8", "-n", "1"], stdout = subprocess.PIPE, stderr = subprocess.PIPE, shell=True)
output = ping.communicate()
pattern = r"time= (\d+\S+)"
re.findall(pattern, output[0].decode('utf-8'))[0]
print(output)
输出为:
IndexError: list index out of range
但是如果我改变
pattern = r"time= \d+\S+)"
至
pattern = r"Average = \d+\S+)"
输出变为:
(b'\r\nPinging 8.8.8.8 with 32 bytes of data:\r\nReply from 8.8.8.8: bytes=32 time=26ms TTL=122\r\n\r\nPing statistics for 8.8.8.8:\r\n Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),\r\nApproximate round trip times in milli-seconds:\r\n Minimum = 26ms, Maximum = 26ms, Average = 26ms\r\n', b'')
它会 ping Google DNS 但不会过滤掉所需的 20 毫秒,理想情况下输出为 20 没有毫秒。
有什么想法是我的小脑袋哪里出了问题吗?谢谢:)
我想下面的内容可能对您有所帮助:
import re
m = re.search(r'time=(\d+)ms', output[0].decode('utf-8'))
if m:
print(m.group(1))
此外,您可能希望将结果转换为 int
,即
if m:
latency = int(m.group(1))
(这不会改变输出,但现在你操纵的是一个数字,而不是一个字符串)。
问题是 space 字符 (</code>) 在等号 <code>=
之前。由于您提供的字符串中有 none,您的正则表达式失败。
将您的正则表达式模式更改为 r'\btime=\s*(\d+)'