本文介绍如何使用 Python 编写程序,实时读取并显示 iperf3 命令的每一行输出。

默认情况下,iperf3 命令的输出是通过缓冲区一次性输出的,这会导致在 Python 程序中使用 iter(process.stdout.readline, '') 只能在 iperf3 运行完成后才能读取所有输出。

为了实现逐行打印,可以将 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()

改进后的代码:

import subprocess
import time

def run_iperf_command():
    command = 'iperf3 -c 192.168.124.92 -p11111 -i 1 > output.txt'
    subprocess.Popen(command, shell=True)
    time.sleep(1)  # 等待 iperf3 开始输出
    with open('output.txt', 'r') as file:
        for line in file:
            print(time.time(), line.strip())

run_iperf_command()

这段代码将 iperf3 的输出重定向到名为 output.txt 的文件中,然后通过逐行读取文件内容,实现了实时打印 iperf3 的输出。

Python 实时读取 iperf3 输出:逐行打印技巧

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

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