我已经通过将import移到顶部声明解决了我的问题,但是这让我感到奇怪:为什么我不能使用'__main__'
在作为目标的函数中导入的模块multiprocessing
?
例如:
import os
import multiprocessing as mp
def run(in_file, out_dir, out_q):
arcpy.RaterToPolygon_conversion(in_file, out_dir, "NO_SIMPIFY", "Value")
status = str("Done with "+os.path.basename(in_file))
out_q.put(status, block=False)
if __name__ == '__main__':
raw_input("Program may hang, press Enter to import ArcPy...")
import arcpy
q = mp.Queue()
_file = path/to/file
_dir = path/to/dir
# There are actually lots of files in a loop to build
# processes but I just do one for context here
p = mp.Process(target=run, args=(_file, _dir, q))
p.start()
# I do stuff with Queue below to status user
当您在IDLE中运行它时,它根本不会出错...只是继续进行Queue
检查(这很好,所以不是问题)。问题是,当您在CMD终端(操作系统或Python)中运行此命令时,会产生arcpy
未定义的错误!
只是一个有趣的话题。
在类似Unix的系统和Windows中,情况有所不同。在Unix系统上,multiprocessing
用于fork
创建共享父存储空间的写时复制视图的子进程。子级可以看到从父级导入的内容,包括父级下导入的任何内容if __name__ == "__main__":
。
在Windows上,没有fork,必须执行一个新进程。但是简单地重新运行父进程是行不通的-它会再次运行整个程序。相反,multiprocessing
运行其自己的python程序,该程序将导入父主脚本,然后对希望对子进程足够的父对象空间视图进行腌制/解开/腌制。
该程序是__main__
针对子进程的__main__
,父脚本的不会运行。就像其他模块一样,导入了主脚本。原因很简单:运行父级__main__
只会再次运行完整的父级程序,mp
必须避免。
这是测试以显示正在发生的情况。主模块称为testmp.py
,第二模块test2.py
由第一个模块导入。
testmp.py
import os
import multiprocessing as mp
print("importing test2")
import test2
def worker():
print('worker pid: {}, module name: {}, file name: {}'.format(os.getpid(),
__name__, __file__))
if __name__ == "__main__":
print('main pid: {}, module name: {}, file name: {}'.format(os.getpid(),
__name__, __file__))
print("running process")
proc = mp.Process(target=worker)
proc.start()
proc.join()
test2.py
import os
print('test2 pid: {}, module name: {}, file name: {}'.format(os.getpid(),
__name__, __file__))
在Linux上运行时,将一次导入test2,并且worker在主模块中运行。
importing test2
test2 pid: 17840, module name: test2, file name: /media/td/USB20FD/tmp/test2.py
main pid: 17840, module name: __main__, file name: testmp.py
running process
worker pid: 17841, module name: __main__, file name: testmp.py
在Windows下,请注意,两次“导入test2”被打印-testmp.py运行了两次。但是“主pid”仅被打印一次-它__main__
没有运行。这是因为在导入期间将multiprocessing
模块名称更改为__mp_main__
。
E:\tmp>py testmp.py
importing test2
test2 pid: 7536, module name: test2, file name: E:\tmp\test2.py
main pid: 7536, module name: __main__, file name: testmp.py
running process
importing test2
test2 pid: 7544, module name: test2, file name: E:\tmp\test2.py
worker pid: 7544, module name: __mp_main__, file name: E:\tmp\testmp.py
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句