python使用subprocess.Popen多线程的cmd命令交互
我们创建了一个CmdThread类,该类继承自threading.Thread,并重写了run()方法,我们使用subprocess.Popen()执行指定的命令,并通过管道获取命令的输出。然后,我们逐行读取输出,并打印到控制台
import subprocess
import threadingclass CmdThread(threading.Thread):def __init__(self, command):threading.Thread.__init__(self)self.command = commanddef run(self):process = subprocess.Popen(self.command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)while True:line = process.stdout.readline().decode("utf-8")if not line:breakprint(line.strip())
我们创建了两个CmdThread实例,并分别启动线程。通过调用start()方法启动线程,并通过调用join()方法等待线程结束。这样,我们就可以同时执行多个命令,并实现多线程的cmd命令交互。
# 创建多个CmdThread实例
cmd1 = CmdThread("ping www.google.com")
cmd2 = CmdThread("dir")# 启动线程
cmd1.start()
cmd2.start()# 等待线程结束
cmd1.join()
cmd2.join()