Python使用線程池傳遞多個參數(shù)的幾種方法
在 Python 中使用線程池傳遞多個參數(shù)有多種方法,以下是幾種常用的方式:
方法一:使用zip和*解包
from concurrent.futures import ThreadPoolExecutor
def worker(phone, x, y, duration):
print(f"設(shè)備: {phone}, 位置: ({x}, {y}), 時長: {duration}")
# 這里執(zhí)行實際的投屏操作
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] # 投屏?xí)r長
with ThreadPoolExecutor(max_workers=3) as executor:
# 使用zip打包參數(shù),然后解包傳遞給worker函數(shù)
executor.map(worker, phones, x_positions, y_positions, durations)
方法二:使用partial函數(shù)固定部分參數(shù)
from concurrent.futures import ThreadPoolExecutor
from functools import partial
def worker(phone, x, y, duration):
print(f"設(shè)備: {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參數(shù)
fixed_worker = partial(worker, x=100, y=100, duration=20)
with ThreadPoolExecutor(max_workers=3) as executor:
executor.map(fixed_worker, phones)
方法三:使用字典或元組包裝參數(shù)
from concurrent.futures import ThreadPoolExecutor
def worker(params):
phone = params['phone']
x = params['x']
y = params['y']
duration = params['duration']
print(f"設(shè)備: {phone}, 位置: ({x}, {y}), 時長: {duration}")
def thread_pool_with_dict():
# 參數(shù)列表
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"設(shè)備: {phone}, 位置: ({x}, {y}), 時長: {duration}")
def thread_pool_with_starmap():
# 參數(shù)元組列表
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解包元組參數(shù)
executor.map(lambda args: worker(*args), args_list)
在您的代碼中應(yīng)用
修改您的代碼以支持多參數(shù)傳遞:
def Scrcpy(params):
"""接收參數(shù)字典的投屏函數(shù)"""
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}")
# 添加窗口位置參數(shù)
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():
# 定義設(shè)備及其參數(shù)
device_configs = [
{'phone': "172.26.101.164", 'x': 100, 'y': 100, 'duration': 20},
{'phone': "172.26.101.112", 'x': 800, 'y': 100, 'duration': 25},
# 添加更多設(shè)備...
]
try:
with ThreadPoolExecutor(max_workers=len(device_configs)) as executor:
executor.map(Scrcpy, device_configs)
except Exception as e:
log(logging.ERROR, f"線程池異常: {e}")
# 在主函數(shù)中使用
if __name__ == '__main__':
while True:
if len(PHONES) >= 2:
selected = random.sample(PHONES, 2)
log(logging.DEBUG, f"--> 隨機選取的投屏設(shè)備:{selected}")
# 為每個設(shè)備創(chuàng)建參數(shù)配置
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)的多參數(shù)傳遞
import multiprocessing
def worker(args):
phone, x, y, duration = args
print(f"設(shè)備: {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方式),因為它:
- 代碼清晰易讀
- 參數(shù)傳遞靈活
- 易于維護和擴展
這樣您就可以為每個設(shè)備指定不同的窗口位置、投屏?xí)r長等參數(shù)了。
到此這篇關(guān)于Python使用線程池傳遞多個參數(shù)的幾種方法的文章就介紹到這了,更多相關(guān)Python線程池傳遞多個參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
只用40行Python代碼就能寫出pdf轉(zhuǎn)word小工具
今天咱們介紹一個pdf轉(zhuǎn)word的免費小工具,滿足這么一個不常見但是偶爾會出來煩人的需求文中有非常詳細的代碼示例,對小伙伴們很有幫助,需要的朋友可以參考下2021-05-05
Python實現(xiàn)讀取文本文件并轉(zhuǎn)換為pdf
這篇文章主要為大家詳細介紹了如何使用Python簡便快捷地完成TXT文件到PDF文檔的轉(zhuǎn)換,滿足多樣化的文檔處理需求,感興趣的小伙伴可以參考下2024-04-04
Expected conditions模塊使用方法匯總代碼解析
這篇文章主要介紹了Expected conditions模塊使用方法匯總代碼解析,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
python使用pycharm環(huán)境調(diào)用opencv庫
這篇文章主要介紹了python使用pycharm環(huán)境調(diào)用opencv庫,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-02-02
opencv python在視屏上截圖功能的實現(xiàn)
OpenCV是一個基于BSD許可(開源)發(fā)行的跨平臺計算機視覺庫,可以運行在Linux、Windows、Android和Mac OS操作系統(tǒng)上。這篇文章主要介紹了opencv python在視屏上截圖,需要的朋友可以參考下2020-03-03
關(guān)于Python中幾種隊列Queue用法區(qū)別
這篇文章主要介紹了關(guān)于Python中幾種隊列Queue用法區(qū)別,queue隊列中的put()或者get()方法中都提供了timeout參數(shù),利用這個參數(shù)可以有效解決上述消除不能消費和線程一直阻塞問題,需要的朋友可以參考下2023-05-05
Python實現(xiàn)HTML文件或字符串轉(zhuǎn)換為純文本TXT
在數(shù)據(jù)處理、內(nèi)容提取、網(wǎng)頁歸檔等任務(wù)中,經(jīng)常需要將 HTML 轉(zhuǎn)換為純文本 TXT,本文將介紹如何用 Python 和 Free Spire.Doc 庫完成 HTML 到 TXT 的轉(zhuǎn)換,希望對大家有所幫助2025-09-09
Python實現(xiàn)簡單線性插值去馬賽克算法代碼示例
去馬賽克是圖像處理中的一項技術(shù),用于從單色彩濾光片陣列(CFA)圖像恢復(fù)全彩圖像,本文介紹了一種基于簡單線性插值的去馬賽克算法,并展示了如何將MATLAB代碼轉(zhuǎn)換為Python代碼,需要的朋友可以參考下2024-10-10

