在Python中,可以使用subprocess模块来执行shell命令。要在多线程中并行执行shell命令,可以使用threading模块来创建线程,然后在线程中调用subprocess模块执行命令。

以下是一个示例代码,展示了如何在多线程中并行执行shell命令,并限制线程数量为5:

import subprocess
import threading
import queue

# 创建线程池
thread_pool = []

# 创建队列,用于存储要执行的shell命令
command_queue = queue.Queue()

# 限制线程数量为5
max_threads = 5

# 定义线程执行的函数
def execute_command():
    while True:
        # 从队列中获取要执行的命令
        command = command_queue.get()
        if command is None:
            # 如果队列中没有命令了,线程退出
            break
        else:
            # 执行命令
            subprocess.call(command, shell=True)
            # 命令执行完成后,通知队列任务完成
            command_queue.task_done()

# 创建并启动线程
for _ in range(max_threads):
    thread = threading.Thread(target=execute_command)
    thread.start()
    thread_pool.append(thread)

# 将要执行的命令加入队列
command_queue.put("command 1")
command_queue.put("command 2")
# ...

# 等待队列中的任务全部完成
command_queue.join()

# 停止线程
for _ in range(max_threads):
    command_queue.put(None)

for thread in thread_pool:
    thread.join()

在上面的代码中,首先创建一个线程池和一个队列。然后定义一个执行命令的函数execute_command,该函数从队列中获取要执行的命令,并调用subprocess.call函数执行命令。命令执行完成后,通知队列任务完成。接下来,创建并启动指定数量的线程,并将要执行的命令加入队列。最后,等待队列中的任务全部完成,停止线程。

希望对你有帮助

Python thread多线程并行执行shell命令及限制线程数量

原文地址: https://www.cveoy.top/t/topic/hXBn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录