yet another confusion with multiprocessing error, 'module' object has no attribute 'f'

前端 未结 5 1418
滥情空心
滥情空心 2020-11-28 07:53

I know this has been answered before, but it seems that executing the script directly \"python filename.py\" does not work. I have Python 2.6.2 on SuSE Linux.

Code:<

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 08:37

    This one works:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    from multiprocessing import Pool
    
    def f(x):
        return x*x
    
    if __name__ == "__main__":
        p = Pool(1)
        p.map(f, [1, 2, 3])
    

    I'm not 100% sure why your code does not work, but I guess the reason is that child processes launched by the multiprocessing module try to import the main module (to have access to the methods you defined), and the if __name__ == "__main__" stanza is required not to execute the initialization code where you set up your pool.

提交回复
热议问题