Python多线程函数

2024-09-28 22:25:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,例如:

launcher(usr_login, usr_password)

它调用其他python脚本+usr\u login+usr\u密码作为参数。在

参见: 功能

^{pr2}$

将执行函数.py文件格式为$function.py login pass
主题: 我有dict user_login:password,我希望能够在一次多线程/多处理中启动“启动器”函数

dict有login1:pass1,login2:pass2 所以我需要同时启动启动器(login1,pass1)和启动器(login2,pass2)。 有办法吗? 谢谢你

# -*- coding: utf-8 -*-
from config import users, ThCount
from time import sleep
from multiprocessing import Pool
import os

users = {}

def launcher(usr_login, usr_password):
    os.system("C:\\Python34\\python.exe implementation.py %s %s" % (usr_login, usr_password))

回复评论#1 如果我这样使用:

def launcher(usr_login, usr_password):
    os.system("C:\\Python34\\python.exe implementation.py %s %s" % (usr_login, usr_password))
if __name__ == '__main__':
    with Pool(5) as p:
        p.map(launcher, users)

我得到了:

TypeError: launcher() missing 1 required positional argument: 'usr_password'

Tags: 函数frompyimportosusrloginpassword
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:47

不能使用Pool.map()向函数传递多个参数。在

作为一个简单的解决方案,您可以将它们打包成元组。在

# -*- coding: utf-8 -*-
from multiprocessing import Pool
import os

users = {
    'a': '1',
    'b': '2',
    'c': '3'
}

def launcher(args):
    os.system("python implementation.py %s %s" % (args[0], args[1]))


if __name__ == '__main__':
    with Pool(3) as p:
        p.map(launcher, users.items())

UPD我注意到您使用的是python3.4。从3.3版开始,您可以使用Pool.starmap传递多个参数,从而保持参数列表的可读性。在

^{pr2}$

相关问题 更多 >