python多進程為什麼一定要__name__="__main__"?
python多進程為什麼一定要__name__="__main__"?
如果一個函數使用了多進程,供其他函數調用,要怎麼寫?
python多進程 沒有必需__name__="__main__"。
但
windows 平台有特殊要求Since Windows has no fork, the multiprocessing module starts a new Python process and imports the calling module. If Process() gets called upon import, then this sets off an infinite succession of new processes (or until your machine runs out of resources). This is the reason for hiding calls to Process() inside
if __name__ == "__main__"
since statements inside this if-statement will not get called upon import.
請看
這樣理解python中的if __name__ == "__main__" - 通過python學會編程 - 知乎專欄小任務寫成函數,再用Process(target=函數名, args=(函數的參數,))
from multiprocessing import Process
import os
def info(title):
print title
print "module name:", __name__
if hasattr(os, "getppid"): # only available on Unix
print "parent process:", os.getppid()
print "process id:", os.getpid()
def f(name):
info("function f")
print "hello", name
if __name__ == "__main__":
info("main line")
p = Process(target=f, args=("bob",))
p.start()
p.join()
推薦閱讀:
※為啥進程池封裝在裝飾器中不能生效,而多進程可以?
※進程間通信和線程間通信的區別?
※如何利用Python抓取PDF中的某些內容?
※pandas 怎麼根據一列的數據的值的情況判斷來生成另外一列的數值?
※如何批量獲取年報中數據?