Python:尝试从控制台获取数据

Python:尝试从控制台获取数据,python,Python,在Python中是否可以从控制台获取一些特定信息?我的意思是,我使用操作系统模块来获取诸如ping之类的信息,或者使用NMAP来将我的活动主机连接到我的网络,诸如此类。如果我向您展示一个示例,可能会更好: import os os.system('cmd /c "ping youtube.com"') 我的输出是: Pinging youtube.com [172.217.192.93] with 32 bytes of data: Reply from 172.217.1

在Python中是否可以从控制台获取一些特定信息?我的意思是,我使用操作系统模块来获取诸如ping之类的信息,或者使用NMAP来将我的活动主机连接到我的网络,诸如此类。如果我向您展示一个示例,可能会更好:

import os
os.system('cmd /c "ping youtube.com"')
我的输出是:

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

正如你所看到的,非常基本,但这是我的问题,我只想得到那些时间(99107171103),所以我可以稍后使用它们。我使用PyCharm,Python版本为3.9。为此,您可以使用标准库中的
子流程
re

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)

您好,谢谢您的回答,与第一个答案相同,它给了我一个类型错误,它说:不能在Objects这样的字节上使用字符串模式没有问题,在声明
输出后添加
output=output.decode('utf-8')
。我将编辑我的答案。