0

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?

ed0
  • 3
  • 2
  • Notice the b prefix refers to bytes, but [the behavior of this is different depending on whether you're using Python 2/3.](http://stackoverflow.com/a/6269785/868044). Even if it were being treated as a string, iterating over it in this fashion would iterate character by character, not word for word (you'd need to use "split()" for that). It looks like you may be using Python 3 in which case you are seeing the integer value of each byte in the value. – Dan Aug 24 '16 at 13:44
  • Be careful though, because different systems have different ping implementations, the output of which varies a lot. For example here is the stats line of the ping command I have around: `round-trip min/avg/max = 2/3/6 ms`. – spectras Aug 24 '16 at 14:04

1 Answers1

2

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
DeepSpace
  • 78,697
  • 11
  • 109
  • 154