在 Python 中使用多处理,导入语句的正确方法是什么?

Using multiprocessing in Python, what is the correct approach for import statements?

PEP 8 状态:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

但是,如果我正在导入的class/method/function只被子进程使用,那么在需要的时候进行导入肯定更有效率吗?我的代码基本上是:

p = multiprocessing.Process(target=main,args=(dump_file,))
p.start()
p.join()
print u"Process ended with exitcode: {}".format(p.exitcode)
if os.path.getsize(dump_file) > 0:
    blc = BugLogClient(listener='http://21.18.25.06:8888/bugLog/listeners/bugLogListenerREST.cfm',appName='main')
    blc.notifyCrash(dump_file)

main() 是主要的应用程序。此函数需要大量导入到 运行 并且这些会占用一些内存 space (+/- 35MB)。作为另一个进程中的应用程序 运行s,导入在 PEP 8 之后进行了两次(一次由父进程进行,另一次由子进程进行)。还应该注意的是,这个函数应该只调用一次,因为父进程正在等待查看应用程序是否崩溃并留下退出代码(感谢 faulthandler)。所以我在主函数中编写了导入代码,如下所示:

def main(dump_file):

    import shutil
    import locale

    import faulthandler

    from PySide.QtCore import Qt
    from PySide.QtGui import QApplication, QIcon

而不是:

import shutil
import locale

import faulthandler

from PySide.QtCore import Qt
from PySide.QtGui import QApplication, QIcon

def main(dump_file):

是否有 'standard' 方法来处理使用多处理完成的导入?

PS:我看过这个 sister question

'standard' 方式是 PEP 8 报告的方式。这就是 PEP 8 的用途:Python.

编码的参考指南

虽然总有例外。本案就是其中之一。

由于Windows 不克隆父进程的内存,因此在生成子进程时,子进程必须re-import 所有模块。 Linux 以更优化的方式处理流程,避免出现此类问题。

我不熟悉 Windows 内存管理,但我会说模块是共享的,不会加载两次。您可能看到的是两个进程的虚拟内存,而不是物理内存。在物理内存上,只应加载模块的一个副本。

是否遵循 PEP 8 取决于您。当资源受到限制时,代码需要进行调整。但如果不需要,请不要 over-optimize 代码!这是错误的做法。