basic use of multiple processes
1 subprocess examples of common functions
You first define a program called by a child process that prints an output statement and gets command-line arguments
1 import sys 2 print ( called_function.py called, Hello World. " ) 3 try : 4 Print ( " got para " , Sys.argv[1:]) 5 except : 6 Span style= "COLOR: #0000ff" >pass
Then define the main function, the parent process, and test the run ()/call ()/Check_call ()/Getstatusoutput ()/GetOutput ()/Ckeck_output functions, respectively.
1 Importsubprocess2 3 #Subprocess.run ()4 Print('---------Subprocess.run------------')5Re = Subprocess.run (['python','called_function.py','para_1','para_2'])6 Print('subprocess.run () test returns obj:', re)7 Print('Return code is: {0}, stdout are: {1}, stderr is: {2}'. Format (Re.returncode, Re.stdout, Re.stderr))8 9 #Subprocess.call ()Ten Print('\ n---------subprocess.call------------') One Print('subprocess.call () test returns code:', Subprocess.call (['python','called_function.py','para_1','para_2'])) A - #Subprocess.ckeck_call () - Print('\ n---------subprocess.check_call------------') the Try: - Print('subprocess.check_call () test returns code:', Subprocess.check_call (['python','called_function.py'])) - exceptsubprocess. Calledprocesserror: - Print('Failed to call.') + - #subprocess.getstatusoutput () + Print('\ n---------subprocess.getstatusoutput------------') A Print('subprocess.getstatusoutput () test returns:', Subprocess.getstatusoutput (['python','called_function.py'])) at - #subprocess.getoutput () - Print('\ n---------subprocess.getstatusoutput------------') - Print('subprocess.getoutput () test returns:', Subprocess.getoutput (['python','called_function.py'])) - - #subprocess.check_output () in Print('\ n---------subprocess.check_output------------') - Print('subprocess.check_output () test returns:', Subprocess.check_output (['python','called_function.py']))
2 Use Popen class interacts with child processes
A function called by a child process is defined first, and an input is required in the function.
1 x = input ('pleaseinput something. ' )2print'Hello world! ' )3# Raise An error4print(y)
To define the function of the parent process again
1 Importsubprocess2 3PRCs = subprocess. Popen (['python','called_function_popen.py'],4stdout=subprocess. PIPE,5stdin=subprocess. PIPE,6Stderr=subprocess. PIPE,7universal_newlines=True,8Shell=True)9 Ten Print('subprocess PID:', Prcs.pid) One ARe = Prcs.communicate ('These string is from stdin') - Print('\nstdout:', re[0]) - Print('\nstderr:', re[1]) the ifprcs.poll (): - Print('\nthe subprocess have been done')
Related reading
1. subprocess Module
Python Threads & Processes & co-process [2]-the basic use of processes--multi-process