python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python线程池传递多个参数

Python使用线程池传递多个参数的几种方法

作者:独隅

本文介绍了在Python中使用线程池传递多个参数的四种方法,并推荐使用stmap方式,这种方法代码清晰易读,参数传递灵活,易于维护和扩展,适用于为每个设备指定不同参数的场景,需要的朋友可以参考下

在 Python 中使用线程池传递多个参数有多种方法,以下是几种常用的方式:

方法一:使用zip和*解包

from concurrent.futures import ThreadPoolExecutor

def worker(phone, x, y, duration):
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")
    # 这里执行实际的投屏操作

def thread_pool_with_zip():
    phones = ["172.26.101.164", "172.26.101.112", "172.26.101.113"]
    x_positions = [100, 500, 900]  # X坐标
    y_positions = [100, 100, 100]  # Y坐标
    durations = [20, 25, 30]  # 投屏时长
    
    with ThreadPoolExecutor(max_workers=3) as executor:
        # 使用zip打包参数,然后解包传递给worker函数
        executor.map(worker, phones, x_positions, y_positions, durations)

方法二:使用partial函数固定部分参数

from concurrent.futures import ThreadPoolExecutor
from functools import partial

def worker(phone, x, y, duration):
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def thread_pool_with_partial():
    phones = ["172.26.101.164", "172.26.101.112", "172.26.101.113"]
    
    # 固定x, y, duration参数
    fixed_worker = partial(worker, x=100, y=100, duration=20)
    
    with ThreadPoolExecutor(max_workers=3) as executor:
        executor.map(fixed_worker, phones)

方法三:使用字典或元组包装参数

from concurrent.futures import ThreadPoolExecutor

def worker(params):
    phone = params['phone']
    x = params['x']
    y = params['y']
    duration = params['duration']
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def thread_pool_with_dict():
    # 参数列表
    params_list = [
        {'phone': "172.26.101.164", 'x': 100, 'y': 100, 'duration': 20},
        {'phone': "172.26.101.112", 'x': 500, 'y': 100, 'duration': 25},
        {'phone': "172.26.101.113", 'x': 900, 'y': 100, 'duration': 30}
    ]
    
    with ThreadPoolExecutor(max_workers=3) as executor:
        executor.map(worker, params_list)

方法四:使用starmap(推荐)

from concurrent.futures import ThreadPoolExecutor

def worker(phone, x, y, duration):
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def thread_pool_with_starmap():
    # 参数元组列表
    args_list = [
        ("172.26.101.164", 100, 100, 20),
        ("172.26.101.112", 500, 100, 25),
        ("172.26.101.113", 900, 100, 30)
    ]
    
    with ThreadPoolExecutor(max_workers=3) as executor:
        # 使用starmap解包元组参数
        executor.map(lambda args: worker(*args), args_list)

在您的代码中应用

修改您的代码以支持多参数传递:

def Scrcpy(params):
    """接收参数字典的投屏函数"""
    phone = params['phone']
    x = params.get('x', 100)  # 默认值
    y = params.get('y', 100)  # 默认值
    duration = params.get('duration', 20)  # 默认值
    
    RestartScrcpy(phone)
    time.sleep(5)
    phone_num = Phone_number(phone)
    
    try:
        _IP_CONNEXT = f"{phone}:12324"
        run_cmd(f"adb connect {_IP_CONNEXT}")  
        # 添加窗口位置参数
        run_cmd(f'scrcpy -s {_IP_CONNEXT} --time-limit {duration} --max-size=1280 --window-title={phone_num} --window-x={x} --window-y={y}') 
        run_cmd(f"adb disconnect {_IP_CONNEXT}")
    except Exception as e:
        log(logging.ERROR, f"Scrcpy: {e}")

def thread_pool_multiple_params():
    # 定义设备及其参数
    device_configs = [
        {'phone': "172.26.101.164", 'x': 100, 'y': 100, 'duration': 20},
        {'phone': "172.26.101.112", 'x': 800, 'y': 100, 'duration': 25},
        # 添加更多设备...
    ]
    
    try:
        with ThreadPoolExecutor(max_workers=len(device_configs)) as executor:
            executor.map(Scrcpy, device_configs)
    except Exception as e:
        log(logging.ERROR, f"线程池异常: {e}")

# 在主函数中使用
if __name__ == '__main__':
    while True:
        if len(PHONES) >= 2:
            selected = random.sample(PHONES, 2)
            log(logging.DEBUG, f"--> 随机选取的投屏设备:{selected}")
            
            # 为每个设备创建参数配置
            configs = []
            for i, phone in enumerate(selected):
                configs.append({
                    'phone': phone,
                    'x': 100 + i * 700,  # 水平排列窗口
                    'y': 100,
                    'duration': 20
                })
            
            thread_pool_multiple_params()
            time.sleep(5)
        # ... 其他条件判断

使用进程池(multiprocessing.Pool)的多参数传递

import multiprocessing

def worker(args):
    phone, x, y, duration = args
    print(f"设备: {phone}, 位置: ({x}, {y}), 时长: {duration}")

def multiprocessing_pool_multiple_params():
    args_list = [
        ("172.26.101.164", 100, 100, 20),
        ("172.26.101.112", 500, 100, 25),
        ("172.26.101.113", 900, 100, 30)
    ]
    
    with multiprocessing.Pool(processes=3) as pool:
        pool.map(worker, args_list)

推荐方案

对于您的场景,我推荐使用方法四(starmap方式),因为它:

  1. 代码清晰易读
  2. 参数传递灵活
  3. 易于维护和扩展

这样您就可以为每个设备指定不同的窗口位置、投屏时长等参数了。

到此这篇关于Python使用线程池传递多个参数的几种方法的文章就介绍到这了,更多相关Python线程池传递多个参数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文