ed0 ed0 - 3 months ago 28
Python Question

Using subprocess to ping an address and get the average ping output in Python?

With this:

import subprocess

hostname = '104.160.142.3'
pingResponse = subprocess.Popen(["ping", hostname, "-n", '1'], stdout=subprocess.PIPE).stdout.read()


I get a string pingResponse:

b'\r\nPinging 104.160.142.3 with 32 bytes of data:\r\nReply from 104.160.142.3: bytes=32 time=159ms TTL=60\r\n\r\nPing statistics for 104.160.142.3:\r\n Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),\r\nApproximate round trip times in milli-seconds:\r\n Minimum = 159ms, Maximum = 159ms, Average = 159ms\r\n'


and I basically want to get the average ms part and store it in another string, but if I try to print out word by word:

for i in pingResponse:
print(i)


I just get a bunch of numbers:

58
32
83
101
110
116
32
61
32
49
44
32
82
101
99
101
105
118
101
100
32
61
32
49
44
32
76
111
115
116
32
61
32
48
32
40
48
37
32
108
111
115
115
41
44
13
10
65
112
112
114
111
120
105
109
97
116
101
32
114
111
117
110
100
32
116
114
105
112
32
116
105
109
101
115
32
105
110
32
109
105
108
108
105
45
115
101
99
111
110
100
115
58
13
10
32
32
32
32
77
105
110
105
109
117
109
32
61
32
52
52
109
115
44
32
77
97
120
105
109
117
109
32
61
32
52
52
109
115
44
32
65
118
101
114
97
103
101
32
61
32
52
52
109
115
13
10


How can I store the average ms into another string?

Answer

You are getting numbers because that is a binary string (note the b in the beginning).

You will need to decode it first, then you can use regex:

import re

s = b'\r\nPinging 104.160.142.3 with 32 bytes of data:\r\nReply from 104.160.142.3: bytes=32 time=159ms TTL=60\r\n\r\nPing statistics for 104.160.142.3:\r\n    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),\r\nApproximate round trip times in milli-seconds:\r\n    Minimum = 159ms, Maximum = 159ms, Average = 159ms\r\n'

s = s.decode()

print(re.search(r'Average = (\d+)', s, re.MULTILINE).group(1))

>> 159
Comments