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

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.

但是,如果我导入的类/方法/函数仅由子进程使用,那么在需要时进行导入肯定会更有效率吗?我的代码基本上是:

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()是主要的应用程序.这个函数需要大量的导入才能运行,并占用一些ram空间(/ – 35MB).当应用程序在另一个进程中运行时,导入将在PEP 8之后完成两次(一次由父进程执行,另一次由子进程执行).还应该注意,只有在父进程等待查看应用程序是否崩溃并离开exitcode时才应调用此函数一次(感谢faulthandler).所以我在main函数中编译了这样的导入:

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):

是否有一种“标准”方法来处理使用多处理完成的导入?

PS:我见过这个sister question

最佳答案 “标准”方式是PEP 8报告的方式.这就是PEP 8的用途:Python编码参考指南.

但总有例外.这个案子就是其中之一.

由于Windows不克隆父进程内存,因此在生成子进程时,子进程必须重新导入所有模块. Linux以更优化的方式处理流程,避免这样的问题.

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

是否遵循PEP 8取决于您.当资源是约束时,代码需要适应.但如果没有必要,不要过度优化代码!这是一种错误的做法.

点赞