【问题标题】:multiprocessing inside async in python 3.8 fails (Can't pickle local object)python 3.8中异步内部的多处理失败(无法腌制本地对象)
【发布时间】:2020-09-25 09:32:40
【问题描述】:

以下代码在 python 3.7 中有效,但在 python 3.8 中无效 (AttributeError: Can't pickle local object 'main.<locals>.f')

import multiprocessing as mp
import asyncio

async def main():
    def f():
        print("hello")

    p = mp.Process(target=f)
    p.start()

if __name__ == "__main__":
    asyncio.run(main())

我知道在异步函数中运行进程并不常见,可能会引起一些人的注意,但我发现它有时很有用。它不再在 python 3.8 中工作的原因是什么?有没有办法更新代码以使其正常工作?

【问题讨论】:

    标签: python multiprocessing python-asyncio python-3.8


    【解决方案1】:

    我刚刚意识到这与异步无关。没有异步它也会失败。解决方法是将f 移出main。不知道为什么现在在 python 3.8 中需要这样做。

    import multiprocessing as mp
    import asyncio
    
    def f():
        print("hello")
    
    async def main():
        p = mp.Process(target=f)
        p.start()
    
    if __name__ == "__main__":
        asyncio.run(main())
    

    【讨论】:

    • 我认为更简单、更干净的解决方案是让它成为一个类?
    • @jacobgalam Python 不是 Java,使用独立函数完全没问题。原代码的问题是函数是在本地定义的,所以不能传给子进程。
    猜你喜欢
    • 2020-09-22
    • 2022-01-02
    • 1970-01-01
    • 2021-06-17
    • 2021-11-10
    • 1970-01-01
    • 1970-01-01
    • 2019-02-19
    • 2019-03-03
    相关资源
    最近更新 更多