if __name__ = = ' Main in Python programming uses multiple processes with Windows

Source: Internet
Author: User

if __name__ = = ' main

A python file has two methods to use, the first is to execute directly as a sequence , and the second is to import into other Python programs called (module reuse) execution .

So if __name__ = = ' main ': The action is to control the process of executing the code in both cases,

In the If __name__ = = ' main ': The code below is executed only in the first case (that is, the file is executed directly as a program), and import is not executed in other programs

First case:

deffunc ():Print('Second')Print(' First')Print(__name__)#when the run itself is executed, the __name__=__main__if __name__=='__main__': func () # When the file is executed separately, Python main_test.py, the output: "" "" "" "" "" "" "First__main__second" "" 

If __name__== "__main__": the code before and after the statement is executed.

Second case:

ImportMain_test#Import main_test Fileif __name__=='__main__':    Print('Main_test2') #  When the file is executed separately, Python mian_test2.py, the output "" "" "in the first # main_test Module print
       main_test # When Main_test is imported, main_test.py print (__name__) output is the name of the import module main_test, not __main__. main_test2"""
Second not being exported?

Main_test is imported, does not satisfy __name__ = = ' __main__ ' so will not output second, that is Main_test "if __name__==": The previous statement was executed, after which it was not executed

Windows Create multi-process

Code One

ImportMultiprocessingImport TimeImportThreadingPrint('Main process Start1')deffunc ():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='number 1th') P.start ()Print('Main process End', Time.asctime (Time.localtime (Time.time ())), multiprocessing.current_process ())if __name__=='__main__':    Pass    #The program does not end until all processes have been completed by default

Execution effect

main process Start1main process end Fri Mar 11:04:46 2018 <_mainprocess (mainprocess, started) >    main process Start1 is equivalent to importing the module
The Windows creation process is equivalent to importing the file, and the module is infinitely recursively imported by the creation process before the main function.
So the
Windows creation process should be placed after the main function, because the main function does not execute the imported module.
Traceback (most recent): File"<string>", Line 1,inch<module>File"C:\Program files\python36\lib\multiprocessing\spawn.py", Line 105,inchSpawn_main ExitCode=_main (FD) File"C:\Program files\python36\lib\multiprocessing\spawn.py", line 114,inch_main Prepare (preparation_data) File"C:\Program files\python36\lib\multiprocessing\spawn.py", line 225,inchPrepare _fixup_main_from_path (data['Init_main_from_path']) File"C:\Program files\python36\lib\multiprocessing\spawn.py", line 277,inch_fixup_main_from_path Run_name="__mp_main__") File"C:\Program files\python36\lib\runpy.py", line 263,inchRun_path Pkg_name=pkg_name, Script_name=fname) File"C:\Program files\python36\lib\runpy.py", line 96,inch_run_module_code mod_name, Mod_spec, Pkg_name, Script_name) File"C:\Program files\python36\lib\runpy.py", line 85,inch_run_codeexec(Code, run_globals) File"C:\Users\china\PycharmProjects\rq3\ concurrent \ Classroom \windows_process.py", line 22,inch<module>P.start () File"C:\Program files\python36\lib\multiprocessing\process.py", Line 105,inchStart Self._popen=Self._popen (self) File"C:\Program files\python36\lib\multiprocessing\context.py", line 223,inch_popenreturn_default_context.get_context (). Process._popen (process_obj) File"C:\Program files\python36\lib\multiprocessing\context.py", Line 322,inch_popenreturnPopen (process_obj) File"C:\Program files\python36\lib\multiprocessing\popen_spawn_win32.py", line 33,inch __init__Prep_data=Spawn.get_preparation_data (process_obj._name) File"C:\Program files\python36\lib\multiprocessing\spawn.py", line 143,inchget_preparation_data _check_not_importing_main () File"C:\Program files\python36\lib\multiprocessing\spawn.py", line 136,inch_check_not_importing_main is  notGoing to is frozen to produce an executable." ") Runtimeerror:an attempt have been made to start a new process before the current process has finished        Its bootstrapping phase. This probably means, you is not using the fork to start your child processes and we have forgotten to use the pro Per idiom in the main module:

Code two

ImportMultiprocessingImport TimeImportThreadingPrint('Main process Start1')deffunc ():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='number 1th') P.start ()Print('Main process End', Time.asctime (Time.localtime (Time.time ())), multiprocessing.current_process ())#The program does not end until all processes have been completed by default

Windows output Results

Main process Start1main process end Fri Mar 11:17:00 2018 <_mainprocess (mainprocess, started) >main process Start1 When a child process is created, import the module output main function before the statement subprocess start Fri Mar 11:17:00 2018  Child Process Execution Funcsubprocess end Fri Mar 23 11:17:03 2018

Output results on Linux

Main process Start1 only outputs one start1main process end Fri Mar 12:29:12 2018 <_mainprocess (mainprocess, started) >subproc ESS start Fri Mar 12:29:12 2018subprocess end Fri Mar 23 12:29:15 2018

if __name__ = = ' Main in Python programming uses multiple processes with Windows

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.