python threading库文件来实现并行执行cmd_lst命令集

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是包含所有要执行的命令的列表。

通过使用线程和信号量,可以确保在给定的最大并发量下,同时执行的命令数量不会超过设定值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值