python - 无法利用多处理共享内存来保存多处理函数的输出

标签 python global-variables python-multiprocessing shared-memory

我正在编写一个程序来从网络中提取信息并将其保存在 Python 列表中。我使用多重处理方法来提取信息,但在保存输出列表以供进一步处理时遇到问题。这是我的代码:

import multiprocessing

def web_scrape1():
    #some codes to scrape the web output 3 lists
    global sub_list1a, sub_list2a, sub_list3a
    sub_list1a.append(scrape1)
    sub_list2a.append(scrape2)
    sub_list3a.append(scrape3)

def web_scrape2():
    #some codes to scrape the web output 3 lists
    global sub_list1b, sub_list2b, sub_list3b
    sub_list1b.append(scrape1)
    sub_list2b.append(scrape2)
    sub_list3b.append(scrape3)

def master_scraper():
    ws1 = multiprocessing.Process(target=web_scrape1)
    ws2 = multiprocessing.Process(target=web_scrape2)

    ws1.start()
    ws2.start()
    ws1.join()
    ws2.join()

    global master_list1, master_list2, master_list3

    master_list1 = sub_list1a + sub_list1b
    master_list2 = sub_list2a + sub_list2b
    master_list3 = sub_list3a + sub_list3b

def postprocessing():
    #some codes to process the lists
    print(master_list1) # Output []
    print(master_list2) # Output []
    print(master_list3) # Output []

def main():
  master_scraper()
  postprocessing()

if __name__ == '__main__':
  multiprocessing.freeze_support()
  main()

上述代码的输出很简单:

[]
[]
[]

我尝试使用 web_scape1() 内的 multiprocessing.Array('b', sub_list1a) 之类的内容将所有列表分配给共享内存,master_scraper()main() 函数,但列表仍然以 [] 形式返回。

希望在这里得到一些帮助。

最佳答案

多处理中,不能使用全局变量,因为进程拥有自己的内存区域,每个进程内部的更改是独立的。完成您正在尝试的事情的最简单方法是使用 Manager 在进程之间进行通信。您可以创建output_container并将其传递给每个函数,以便它们可以访问它并修改它。例如:

import multiprocessing as mp


def web_scrape1(output_container: list):
    sample_text = 'value from web_scrape1'
    output_container.append(sample_text)


def web_scrape2(output_container: list):
    sample_text = 'value from web_scrape2'
    output_container.append(sample_text)


if __name__ == "__main__":
    output_container = mp.Manager().list()

    worker1 = mp.Process(target=web_scrape1, args=(output_container,))
    worker2 = mp.Process(target=web_scrape2, args=(output_container,))

    worker1.start()
    worker2.start()

    worker1.join()
    worker2.join()

    print(output_container)
    >>> ['value from web_scrape1', 'value from web_scrape2']

您可以在docs中找到更多信息.

关于python - 无法利用多处理共享内存来保存多处理函数的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60069434/

相关文章:

python - 池.apply_async() : nested function is not executed

Python 多处理子类初始化

python - NumPy 中的多处理

python - PIL 不会导入_imaging C 模块 : "*** The _imaging C module is not installed"

Python SQlite。 LIMIT 变量在循环中不改变值

以全局变量为数据源的 PHP session 副作用警告

go - 我应该避免在 golang 中使用包单例吗?

python - 将整数日期时间转换为日期时间格式

python - 为什么这个提供的正则表达式返回 true?

php - Zend Framework 2 设置全局模块变量