python編程中的if __name__ == 'main與windows中使用多進程

if __name__ == 'main

一個python的文件有兩種使用的方法,第一是直接做爲序執行,第二是import到其餘的python程序中被調用(模塊重用)執行python

所以if __name__ == 'main': 的做用就是控制這兩種狀況執行代碼的過程,bootstrap

在if __name__ == 'main': 下的代碼只有在第一種狀況下(即文件做爲程序直接執行)纔會被執行,而import到其餘程序中是不會被執行的windows

第一種狀況:併發

def func():
    print('second')
print('first')

print(__name__)  # 當運行自身被執行的時候,__name__=__main__
if __name__ == '__main__':
    func()


#當單獨執行該文件時,即python main_test.py,輸出結果:
""" first __main__ second """

if __name__=="__main__": 語句以前和以後的代碼都被執行。app

第二種狀況:函數

import main_test # 導入main_test文件

if __name__ == '__main__':
    print('main_test2')

# 當單獨執行該文件時,即python mian_test2.py,輸出結果
""" first # main_test模塊中的print main_test # 當main_test被導入時, main_test.py中print(__name__) 輸出爲導入模塊的名稱main_test,而不是__main__。 main_test2 """
second沒有被輸出?

 main_test被導入後,不知足__name__ == '__main__' 因此不會輸出second,即main_test中的if __name__=="__main__": 以前的語句被執行,以後的沒有被執行spa

 

Windows建立多進程

代碼一code

import multiprocessing
import time
import threading

print('main process start1')
def func():
    print('subprocess start',time.asctime(time.localtime(time.time())))
    time.sleep(3)
    print('subprocess end',time.asctime(time.localtime(time.time())))

p = multiprocessing.Process(target=func, name='1號')
p.start()

print('main process end', time.asctime(time.localtime(time.time())),multiprocessing.current_process())
if __name__ == '__main__':
    pass
    # 默認全部進程結束後,程序才結束

執行效果blog

main process start1 main process end Fri Mar 23 11:04:46 2018 <_MainProcess(MainProcess, started)> main process start1 至關於導入該模塊
windows創造進程至關於導入該文件,因爲建立進程在main函數以前,會無限遞歸導入模塊建立進程。
因此在
windows創造進程應放在main函數以後,由於main函數不會執行被導入模塊。
 Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main exitcode = _main(fd) File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 114, in _main prepare(preparation_data) File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 225, in prepare _fixup_main_from_path(data['init_main_from_path']) File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path run_name="__mp_main__") File "C:\Program Files\Python36\lib\runpy.py", line 263, in run_path pkg_name=pkg_name, script_name=fname) File "C:\Program Files\Python36\lib\runpy.py", line 96, in _run_module_code mod_name, mod_spec, pkg_name, script_name) File "C:\Program Files\Python36\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "C:\Users\china\PycharmProjects\rq3\併發\課堂\windows_process.py", line 22, in <module> p.start() File "C:\Program Files\Python36\lib\multiprocessing\process.py", line 105, in start self._popen = self._Popen(self) File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 223, in _Popen return _default_context.get_context().Process._Popen(process_obj) File "C:\Program Files\Python36\lib\multiprocessing\context.py", line 322, in _Popen return Popen(process_obj) File "C:\Program Files\Python36\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__ prep_data = spawn.get_preparation_data(process_obj._name) File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 143, in get_preparation_data _check_not_importing_main() File "C:\Program Files\Python36\lib\multiprocessing\spawn.py", line 136, in _check_not_importing_main is not going to be frozen to produce an executable.''') RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module:

 代碼二遞歸

import multiprocessing
import time
import threading

print('main process start1')
def func():
    print('subprocess start',time.asctime(time.localtime(time.time())))
    time.sleep(3)
    print('subprocess end',time.asctime(time.localtime(time.time())))


if __name__ == '__main__': #把進程建立放在main函數中
    p = multiprocessing.Process(target=func, name='1號')
    p.start()
    print('main process end', time.asctime(time.localtime(time.time())), multiprocessing.current_process())
    # 默認全部進程結束後,程序才結束

Windows輸出結果

main process start1 main process end Fri Mar 23 11:17:00 2018 <_MainProcess(MainProcess, started)> main process start1 子進程建立時,導入該模塊輸出main函數以前語句 subprocess start Fri Mar 23 11:17:00 2018 子進程執行func subprocess end Fri Mar 23 11:17:03 2018

 在Linux上輸出結果

main process start1 只輸出一個start1 main process end Fri Mar 23 12:29:12 2018 <_MainProcess(MainProcess, started)> subprocess start Fri Mar 23 12:29:12 2018 subprocess end Fri Mar 23 12:29:15 2018
相關文章
相關標籤/搜索