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() 是主应用程序。此函数需要大量导入才能运行,并且会占用一些内存空间 (+/- 35MB)。当应用程序在另一个进程中运行时,导入在 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):
是否有“标准”方式来处理使用多处理完成的导入?
PS:我看过这个sister question
最佳答案
“标准”方式是 PEP 8 报告的方式。这就是 PEP 8 的用途:Python 编码的引用指南。
虽然总有异常(exception)。本案就是其中之一。
由于 Windows 不会克隆父进程的内存,因此在派生子进程时,子进程必须重新导入所有模块。 Linux 以更优化的方式处理流程,避免出现此类问题。
我不熟悉 Windows 内存管理,但我会说模块是共享的,不会加载两次。您可能看到的是两个进程的虚拟内存,而不是物理内存。在物理内存上,只应加载模块的一个副本。
是否遵循 PEP 8 取决于您。当资源受到限制时,代码需要进行调整。但是如果没有必要,不要过度优化代码!这是错误的做法。
关于python - 在 Python 中使用多处理,导入语句的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34619347/