|
发表于 2023-10-12 21:46:06
|
显示全部楼层
问题出在 args 参数上,应该将参数作为一个元组传递进去,即 (cmd,) 。修改后的代码如下:
- import subprocess
- import threading
- # 定义一个函数,用于执行一个命令,并打印输出和错误信息
- def run_command(cmd):
- # 创建一个子进程,执行命令,并捕获标准输出和标准错误
- process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- # 读取输出和错误信息
- output, error = process.communicate()
- # 打印输出和错误信息
- print(f"Output of {cmd}:")
- print(output.decode())
- print(f"Error of {cmd}:")
- print(error.decode())
- # 定义一个列表,存储要执行的命令
- commands = ["ls"]
- # 创建一个空列表,用于存储线程对象
- threads = []
- # 遍历命令列表,为每个命令创建一个线程,并启动线程
- for cmd in commands:
- # 创建一个线程对象,指定目标函数和参数
- thread = threading.Thread(target=run_command, args=(cmd,))
- # 将线程对象添加到线程列表中
- threads.append(thread)
- # 启动线程
- thread.start()
- # 遍历线程列表,等待每个线程结束
- for thread in threads:
- # 等待线程结束
- thread.join()
复制代码 |
|