1

Is it possible to get some specific info from the console in Python? I mean, i use the OS module in order to get information like ping, or using NMAP in order to get my active hosts connected to my network, stuff like that. It might be better if I show you an example:

import os
os.system('cmd /c "ping youtube.com"')

And my output is this:

Pinging youtube.com [172.217.192.93] with 32 bytes of data:
Reply from 172.217.192.93: bytes=32 time=99ms TTL=105
Reply from 172.217.192.93: bytes=32 time=107ms TTL=105
Reply from 172.217.192.93: bytes=32 time=171ms TTL=105
Reply from 172.217.192.93: bytes=32 time=103ms TTL=105

Ping statistics for 172.217.192.93:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 99ms, Maximum = 171ms, Average = 120ms

Process finished with exit code 0

Very basic as you can see, but here is my problem, I only want to get those times (99, 107, 171, 103), so I can use them later. I use PyCharm and the version of Python is 3.9

Marcelo
  • 13
  • 3

1 Answers1

1

For this, you can use subprocess and re, both in the standard library:

import re
import subprocess

# Load the process output as a string to a variable
output = subprocess.check_output(["cmd", "/c", "ping youtube.com"])
output = output.decode('utf-8')

# Create a regular expression that finds those times
pattern = re.compile(r"time=(\d+)ms")
values = [int(match) for match in pattern.findall(output)]

print(values)
enzo
  • 9,861
  • 3
  • 15
  • 38
  • Hi thank you for the answer, same as the first answer, it gives me a TypeError, it says: cannot use a string pattern on a bytes-like object – Marcelo Jun 06 '21 at 22:24
  • No problem, add `output = output.decode('utf-8')` after declaring `output`. I'll edit my answer. – enzo Jun 06 '21 at 22:33