Python 实时读取并显示 iperf3 命令输出
Python 实时读取并显示 iperf3 命令输出
本文介绍使用 Python 编写程序,实时读取并显示 iperf3 命令的输出内容。通过 subprocess 模块执行 iperf3 命令,并利用循环读取输出流,实现实时打印功能。
代码示例
import subprocess
import time
def run_iperf_command():
command = 'iperf3 -c 192.168.124.92 -p11111 -i 1'
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE, universal_newlines=True)
for line in iter(process.stdout.readline, ''):
print(time.time(), line.strip())
run_iperf_command()
代码解析
- 导入模块: 导入
subprocess模块用于执行命令,time模块用于获取当前时间。 - 定义函数: 定义
run_iperf_command函数,该函数用于执行 iperf3 命令并读取输出。 - 创建进程: 使用
subprocess.Popen创建一个子进程,并指定stdout=subprocess.PIPE将子进程的标准输出重定向到管道,universal_newlines=True将输出设置为文本模式。 - 循环读取输出: 使用
iter(process.stdout.readline, '')创建一个迭代器,并循环读取子进程的输出,直到读取到空行为止。 - 打印输出: 在每次循环中,打印当前时间和读取到的输出内容,并使用
strip()方法去除空格。
运行程序
保存以上代码为 iperf_output.py 文件,运行该文件即可实时显示 iperf3 命令的输出结果。
注: 您需要根据实际情况修改代码中的 iperf3 命令参数。
总结
本文通过 Python 代码示例展示了如何实时读取并显示 iperf3 命令的输出内容。该方法适用于需要实时监控网络性能的场景。
原文地址: https://www.cveoy.top/t/topic/qzE7 著作权归作者所有。请勿转载和采集!