【问题标题】:Getting real time output from iperf3 using python's subprocess使用 python 的子进程从 iperf3 获取实时输出
【发布时间】:2020-05-11 19:36:16
【问题描述】:

这是一个后续:Getting realtime output using subprocess

我正在尝试使用 subprocess 实时捕获 iperf3 的输出(在 Windows 上使用 python 3.6)。目标是让 iperf3 会话持续运行并获取数据以更新实时图。

我根据引用的问题创建了一个实现(请参阅帖子末尾的代码),但代码仍在等待 iperf3 会话完成的第一个“readline”调用。

输出和期望的行为

我的代码返回输出:

Iperf test
Popen returns after: 0.012966156005859375 seconds
Readline 0 returned after: 3.2275266647338867 seconds, line was: Connecting to host 10.99.99.21, port 5201
Readline 1 returned after: 3.2275266647338867 seconds, line was: [  4] local 10.99.99.7 port 55563 connected to 10.99.99.21 port 5201
Readline 2 returned after: 3.2275266647338867 seconds, line was: [ ID] Interval           Transfer     Bandwidth
Readline 3 returned after: 3.2275266647338867 seconds, line was: [  4]   0.00-0.50   sec  27.4 MBytes   458 Mbits/sec
Readline 4 returned after: 3.2275266647338867 seconds, line was: [  4]   0.50-1.00   sec  29.0 MBytes   486 Mbits/sec
Exited

输出显示第一个 readline 调用直到 3 秒后 iperf 会话完成后才返回。期望的行为是 readline 调用 0、1 和 2 几乎立即返回,而 readline 调用 #3 在大约之后返回。 0.5 秒,一旦 iperf3 完成第一个 0.5 秒报告间隔。

代码

import subprocess
import time

if __name__ == "__main__":
    print('Iperf test')
    tref = time.time()

    reads_to_capture = 5
    times = [0] * reads_to_capture
    lines = [''] * reads_to_capture

    interval = 0.5
    ip = '10.99.99.21' # Iperf server IP address
    process = subprocess.Popen(f'iperf3 -c {ip} -f m -i {interval} -t 3', encoding = 'utf-8',
            stdout=subprocess.PIPE)

    print(f'Popen returns after: {time.time() - tref} seconds')

    cnt = 0

    while True:
        output = process.stdout.readline()
        if cnt < reads_to_capture: # To avoid flooding the terminal, only print the first 5
            times[cnt] = time.time() - tref
            lines[cnt] = output
            cnt = cnt + 1
        if output == '': 
            rc = process.poll()
            if rc is not None:
                break

    rc = process.poll()

    for ii in range(reads_to_capture):
        print(f'Readline {ii} returned after: {times[ii]} seconds, line was: {lines[ii].strip()}')

    print('Exited')

【问题讨论】:

    标签: python subprocess iperf


    【解决方案1】:

    对不起,我的回答迟了。有一个用于 Iperf3 的 API,幸运的是,它带有标准的 iperf3 构建/安装。

    此 API 允许 python 获取 iperf3 的公共输出。

    我给你iperf3的python wrapper的官网。它带有简单的示例供您使用。希望我能给你一个答案。

    https://iperf3-python.readthedocs.io/en/latest/index.html

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center。
    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    猜你喜欢
    • 2015-06-08
    • 2010-10-22
    • 2021-04-15
    • 2021-01-18
    • 2019-01-25
    • 2022-06-19
    相关资源
    最近更新 更多