Purpose: Sequential execution process inside bash like a.sh && b.sh && c.sh
First of all, the Popen function.
class subprocess. Popen (args, bufsize=0, executable=none, stdin=none, stdout=none , stderr=none, preexec_fn=none, close_fds=false,
shell=false, cwd=none, env=none, universal_newlines=false, startupinfo= None,creationflags=0)
- args child process cmd
- bufsize Default is 20K
- stdin Standard input
- STDOUT standard output
- STDERR standard Error
- Other parameters skipped .....
- Popen. poll () Check if child process terminates, return ReturnCode
- Popen. wait () waiting for the child process to terminate, return ReturnCode, it should be noted that if Popen executes the command, set stdout=pipe or stderr=pipe, the child process will produce enough output, This will cause the OS's pipeline cache to be blocked by the time it takes to get the data, which requires the communicate () function.
- Popen. Communicate (input=none) This is a method of interacting with the process that sends the data to the child process's standard input until the process is finished. If you do not require the transfer of data to the child process settings Input=none
-
-
communicate () returns a tuple (stdoutdata, stderrdata).
If you want to send data to the child process standard input, you need to set the stdin=pipewhen creating the Popen. If you want to get information from a tuple, you have to set stdout=pipe or/and stderr=pipe.
This method of data is read after the cache in memory, if the amount of data is very large do not recommend this method
Example:
Import subprocess
Import OS
Import Sys
def run_application (command):
Try
Process = subprocess. Popen (command, stdout=subprocess. PIPE, Stderr=subprocess. PIPE)
communicate = Process.communicate (Input=none)
Return communicate
Except Exception:
Print "Error"
Sys.exit (-1)
if __name__ = = "__main__":
cmd = "ls"
result = Run_application (cmd)
If RESULT[0]:
Run_application (CMD)
print "Done"
Python subprocess Popen