在Python中,可以使用subprocess模块来执行shell命令。要实现多线程并行执行shell命令,并且限制线程数量,可以使用concurrent.futures.ThreadPoolExecutor类。

下面是一个示例代码,演示了如何使用多线程并行执行shell命令,并限制线程数量为4:

import subprocess
import concurrent.futures

def execute_command(command):
    process = subprocess.Popen(command, shell=True)
    process.communicate()
    return process.returncode

if __name__ == '__main__':
    commands = [
        'echo "Command 1"',
        'echo "Command 2"',
        'echo "Command 3"',
        'echo "Command 4"',
        'echo "Command 5"',
        'echo "Command 6"',
        'echo "Command 7"',
        'echo "Command 8"',
        'echo "Command 9"',
        'echo "Command 10"',
    ]

    max_threads = 4

    with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor:
        results = executor.map(execute_command, commands)
    
    for result in results:
        print(result)

在上述代码中,首先定义了一个execute_command函数,用于执行shell命令。execute_command函数使用subprocess.Popen方法执行命令,并通过communicate方法来等待命令执行完成,并获取返回码。

然后,在主程序中定义了一个commands列表,其中包含了要执行的shell命令。

接下来,通过concurrent.futures.ThreadPoolExecutor类来创建一个线程池,指定最大线程数为4。然后使用executor.map方法来将execute_command函数应用到commands列表中的每个命令,并返回一个迭代器,用于获取每个命令的返回结果。

最后,使用for循环打印每个命令的返回结果。

这样,就实现了多线程并行执行shell命令,并限制了线程数量

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

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

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