python列表内有很多字典参数,需要传递给执行函数运行,我想使用多线程运行,线程数是可以自定义的,我应该怎么实现这个功能?
我有一个列表字典:
my_list = [{'ip':'192.168.1.2','password':'123456','user_name':'654321'},{'ip':'192.168.1.3','password':'123456','user_name':'654321'},{'ip':'192.168.1.4','password':'123456','user_name':'654321'},{'ip':'192.168.1.5','password':'123456','user_name':'654321'},
{'ip':'192.168.1.6','password':'123456','user_name':'654321'}]
我有一个执行函数
def dosome(ip,password,user_name):
run.....
我应该怎么使用多线程进行传递参数并运行dosome(ip,password,user_name)?并且线程数我是可以设置的,比如,我线程数设置2个,第一次2个线程执行
dosome(ip='192.168.1.2',password='123456',user_name='654321')dosome(ip='192.168.1.3',password='123456',user_name='654321')
上线线程跑完了才开始执行后面的
dosome(ip='192.168.1.4',password='123456',user_name='654321')dosome(ip='192.168.1.5',password='123456',user_name='654321')
直到最后执行完所有的列表内的字典参数
dosome(ip='192.168.1.6',password='123456',user_name='654321')
回答:
ThreadPoolExecutor
线程池即可
python"># -*- coding: UTF-8 -*-__author__ = 'lpe234'
import time
from concurrent.futures import ThreadPoolExecutor
import threading
my_list = [
{'ip': '192.168.1.2', 'password': '123456', 'user_name': '654321'},
{'ip': '192.168.1.3', 'password': '123456', 'user_name': '654321'},
{'ip': '192.168.1.4', 'password': '123456', 'user_name': '654321'},
{'ip': '192.168.1.5', 'password': '123456', 'user_name': '654321'},
{'ip': '192.168.1.6', 'password': '123456', 'user_name': '654321'}
]
def dosome(ip, password, user_name):
tname = threading.current_thread().getName()
time.sleep(1)
print(f'{tname} {ip}')
tpe = ThreadPoolExecutor(max_workers=3)
for m in my_list:
tpe.submit(dosome, **m)
以上是 python列表内有很多字典参数,需要传递给执行函数运行,我想使用多线程运行,线程数是可以自定义的,我应该怎么实现这个功能? 的全部内容, 来源链接: utcz.com/p/938811.html