python多线程/进程问题:以iperf3为例

多线程/进程问题:以iperf3为例

在给一个项目写可视化的时候,项目需要用iperf3来进行网络测试。

ipef3分为服务器server端和客户client端两个进程,一般使用cmd打开,开启测试的界面是这个样子:

server端
在这里插入图片描述

client端:
在这里插入图片描述

第一个坑

为了能够使用python代码控制控制台打开iperf3.exe,使用subprocess模块来启动。

但是subprocess直接启动程序,需要将iperf3.exe的路径加入到系统变量里,这样就不需要cmd进入对应文件目录再启动:
在这里插入图片描述

第二个坑

在解决直接用命令打开ipef3.exe之后,就是用subprocess使用iperf3.exe -siperf3.exe -c 127.0.0.1这两个命令,应该这样写:

def server():
    with subprocess.Popen(["iperf3.exe", "-s"], stdout=subprocess.PIPE, universal_newlines=True) as process:
        while True:
            print("doing")
            output = process.stdout.readline()
            if output == '' and process.poll() is not None:
                break
            if output:
                # with open('D:\ForStudy\python练习\练习\项目\out.txt', 'w+') as file:
                #     sys.stdout = file             
                #     print(output.strip())
                # sys.stdout = stdout#结果重定向到文档
                a=output.strip()
        rc = process.poll()

注意subprocess.Popen(["iperf3.exe", "-s"],只有这样写,才是正确的输入参数的格式,将-s这个参数和前面分开!!!!!

第三个坑

虽然我现在能够启动server和client并且实现了iperf推流,但是在这两个线程退出之后,我的vscode调试界面居然没有退出!!

在这里插入图片描述

后来仔细想想,我是调用了个线程开启了iperf这个进程,因此虽然这次推流结束了但是iperf server服务进程还在,因此我还需要将这个进程退出才行:

if flag ==1:
    print("client has shut")
    with subprocess.Popen("taskkill /IM iperf3.exe /F", stdout=subprocess.PIPE, shell=True,universal_newlines=True) as process:
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
        	break
        if output:
        	print(output.strip())

这样,我就输入cmd命令将进程关闭了hhhh。简单粗暴又好用:在这里插入图片描述

感谢:雷学长

猜你喜欢

转载自blog.csdn.net/QinZheng7575/article/details/110297077