【发布时间】:2015-05-01 17:36:53
【问题描述】:
我想捕获字符串中某个单词后面的一些字符。例如,
Pinging 10.1.1.1 with 32 bytes of data:
Reply from 10.1.1.1: bytes=32 time=39ms TTL=253
Reply from 10.1.1.1: bytes=32 time=17ms TTL=253
Reply from 10.1.1.1: bytes=32 time=17ms TTL=253
Reply from 10.1.1.1: bytes=32 time=17ms TTL=253
Ping statistics for 10.1.1.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds:
Minimum = 17ms, Maximum = 39ms, Average = 22ms
我想在 time= 之后获取字符,但在第一个 time= 实例的 TTL 之前停止空格
我知道我可以对 time= 进行拆分并获取后面的字符,但我不知道如何让它在 TTL 之前停止(例如,数字可能超过 2 位,所以只需获取 4以下不是一个选项)
也许正则表达式也是一种选择?我已经看到像(?:time=).* 这样的东西会获得第一个实例,但是我再次不确定如何指定它在 ms 之后停止。
编辑 - 添加最终代码,现在它正在工作。感谢大家的帮助!
import os
import subprocess
import re
#Define Target
hostname = raw_input("Enter IP: ")
#Run ping and return output to stdout.
#subprocess.Popen runs cmdline ping, pipes the output to stdout. .stdout.read() then reads that stream data and assigns it to the ping_response variable
ping_response = subprocess.Popen(["ping", hostname, "-n", '1'], stdout=subprocess.PIPE).stdout.read()
word = "Received = 1"
latency = 1
p = re.compile(ur'(?<=time)\S+')
x = re.findall(p, ping_response)
if word in ping_response:
print "Online with latency of "+x[0]
else:
print "Offline"
【问题讨论】:
-
你是如何运行 ping 的?
-
@PadraicCunningham 我将我正在使用的代码添加到问题中。谢谢!
-
@PadraicCunningham 是的。
-
好吧,我想说你可以用 grep 输出,因为它是 windows,更简单的方法是简单地使用 check_output