使用 Python 运行一段命令 "ping 1.1.1.1",并实时打印其输出内容:可以使用 `subprocess` 模块来运行命令并实时打印输出。下面是一个示例代码:

import subprocess

# 定义命令
command = \"ping 1.1.1.1\"

# 运行命令并实时打印输出
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
    output = process.stdout.readline()
    # 如果没有输出,表示命令执行完毕,跳出循环
    if not output and process.poll() is not None:
        break
    if output:
        print(output.strip().decode())

# 获取命令的返回值
returncode = process.poll()
print(f\"命令执行完毕,返回值:{returncode}\")

运行上述代码,将会输出类似以下内容的结果:

正在 Ping 1.1.1.1 具有 32 字节的数据:
来自 1.1.1.1 的回复: 字节=32 时间=2ms TTL=58
来自 1.1.1.1 的回复: 字节=32 时间=2ms TTL=58
来自 1.1.1.1 的回复: 字节=32 时间=2ms TTL=58
来自 1.1.1.1 的回复: 字节=32 时间=2ms TTL=58

1.1.1.1 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 2ms,最长 = 2ms,平均 = 2ms
命令执行完毕,返回值:0
Python 实时打印 ping 命令输出:使用 subprocess 模块

原文地址: https://www.cveoy.top/t/topic/qyt8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录