import subprocess
import threading
def execute_command(command):
process = subprocess.Popen(command, shell=True)
process.communicate()
def run_commands(cmd_lst, max_concurrency):
num_commands = len(cmd_lst)
semaphore = threading.BoundedSemaphore(max_concurrency)
threads = []
def run_with_semaphore(command):
with semaphore:
execute_command(command)
for command in cmd_lst:
thread = threading.Thread(target=run_with_semaphore, args=(command,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print("All commands executed.")
# 示例使用:
commands = ["echo Hello", "dir", "ping www.google.com", "ipconfig"]
max_concurrency = 2
run_commands(commands, max_concurrency)
在上面的示例中,execute_command
函数用于执行给定的命令。run_commands
函数利用threading.BoundedSemaphore
来控制最大并发数。cmd_lst
是包含所有要执行的命令的列表。
通过使用线程和信号量,可以确保在给定的最大并发量下,同时执行的命令数量不会超过设定值。