如何为多处理池中的单个进程分配 python 请求会话?

Nix*_*ill 5 python session python-3.x python-requests python-multiprocessing

考虑以下代码示例:

import multiprocessing
import requests

session = requests.Session()
data_to_be_processed = [...]

def process(arg):
    # do stuff with arg and get url
    response = session.get(url)
    # process response and generate data...
    return data

with multiprocessing.Pool() as pool:
    results = pool.map(process, data_to_be_processed)
Run Code Online (Sandbox Code Playgroud)

例如,Session被分配为全局变量,因此在其中创建进程Pool后将被复制到每个子进程中。我不确定会话是否是线程安全的,也不知道会话中的池是如何工作的,所以我想为 pool 中的每个进程分配单独的会话对象

我知道,我可以使用requests.get(url)而不是session.get(url),但我想使用 session 并且我也在考虑使用requests-htmlhttps://html.python-requests.org/)。

我对python的多处理不是很熟悉,到目前为止我只使用了池,因为它是我认为并行处理数据而没有临界区的最佳解决方案,所以我对不同的解决方案持开放态度。

有没有办法做到干净和直接?

Tim*_*sov 1

简短的回答:您可以使用全局命名空间在初始化程序func之间共享数据:

import multiprocessing
import requests

session = None
data_to_be_processed = [...]

def init_process():
    global session
    session = requests.Session()

def process(arg):
    global session
    # do stuff with arg and get url
    response = session.get(url)
    # process response and generate data...
    return data

with multiprocessing.Pool(initializer=init_process) as pool:
    results = pool.map(process, data_to_be_processed)
Run Code Online (Sandbox Code Playgroud)

长答案:Python 使用三种可能的启动方法之一。它们都将父进程和子进程之间的内存对象分开。在我们的例子中,这意味着Pool()运行的进程的全局命名空间的更改不会传播回父进程,也不会传播回兄弟进程。

对于对象销毁,我们可以依靠垃圾收集器,它会在子进程完成其工作后介入。multiprocessing.Pool()中缺少显式关闭方法使得无法与 GC 无法破坏的对象一起使用(例如Pool()本身 - 请参阅此处的警告)从requests 文档来看,使用requests.Session是完全可以的没有明确的 close() 。