无法获得属性&#39; function_inner&#39; on <module'__mp_main __'=“”from =“”'e:\\ python \\ test \\ test.py'=“”>

时间:2017-04-12 12:32:56

标签: python

我试图在Windows 10中运行python脚本,该脚本已在macOS中运行成功。 然后它抛出一个异常。 运行以下测试程序后:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import multiprocessing


def function_def(*args, **kwargs):
    print('run success')


if __name__ == '__main__':
    def function_inner(*args, **kwargs):
        print('run success')
    process = multiprocessing.Process(target=function_inner)
    process.start()
    process.join()

抛出以下异常:

Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main
exitcode = _main(fd)
File "C:\Users\xxx\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 115, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Can't get attribute 'function_inner' on <module '__mp_main__' from 'E:\\python\\Test\\test.py'>

但是,如果使用

process = multiprocessing.Process(target=function_def)

不适用于

process = multiprocessing.Process(target=function_inner)

然后它成功运行

我使用的是python 3.6.1,windows 10 x64,那我该怎么办?

2 个答案:

答案 0 :(得分:1)

multiprocessing库复制主模块时,它不会将其作为__main__脚本运行,因此if __name__ == '__main__'中定义的任何内容都未在子进程命名空间中定义。因此,AttributeError

答案 1 :(得分:0)

仅当您将脚本作为主脚本运行时,才会定义

function_inner

multiprocessing将在新流程中导入您的模块并尝试调用您的函数,例如

import test
test.function_inner()

但是,if __name__ == '__main__'会评估False,并且不会定义function_inner