如何使用python动态创建进程

时间:2018-06-03 01:36:04

标签: python multithreading process multiprocessing

有没有办法动态生成进程来处理同一批数据。

假设我使用三个不同的帐户与同一个机器人聊天,我无法找出任何方便的方法,所以我只是手动创建流程

def chat(bot, query_list):
        for idx, query in enumerate(query_list):
            answer = bot.chat(query)
            print(answer)

#Let say there is a function called bot, parameter is account information
robot1 = bot(account1)
robot2 = bot(account2)
robot3 = bot(account3)

p1 = multiprocessing.Process(target=chat, args=(robot1, data[0],))
p2 = multiprocessing.Process(target=chat, args=(robot2, data[1],))
p3 = multiprocessing.Process(target=chat, args=(robot3, data[2],))


p1.start()
p2.start()
p3.start()

p1.join()
p2.join()
p3.join()
print('Done!')

但这种方式有点僵硬,因为如果我有大量帐户,我必须手动创建大量流程。那么有没有任何函数或pythonic方法来实现相同的目的?

1 个答案:

答案 0 :(得分:2)

您可以使用流程池来创建动态数量的流程,并将您的任务表示为正确分离的工作以分配工作:

from multiprocessing import Pool

# each entry of `job_list` contains all the information
# required to perform a single task.
job_list = [
    {
        "account": {
            "username": "john",
            "password": "qwerty"
        },
        "query": "How can I help you?"
    } # , ...
]

# function executed for each element of `job_list`
def run_job(job):
    print("account user name: {}".format(job["account"]["username"]))
    print("query: {}".format(job["query"]))
    # answer query here using account

with Pool(processes=4) as pool:
    pool.map(run_job, job_list)