做网站软件dw,网站规划的特点,seo优化业务员招聘,新媒体h5是什么python使用subprocess.Popen多线程的cmd命令交互
我们创建了一个CmdThread类#xff0c;该类继承自threading.Thread#xff0c;并重写了run()方法,我们使用subprocess.Popen()执行指定的命令#xff0c;并通过管道获取命令的输出。然后#xff0c;我们逐行读取输出#…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, shellTrue, stdinsubprocess.PIPE, stdoutsubprocess.PIPE, stderrsubprocess.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()