Use python to execute linux commands and pythonlinux commands
Python version 2.7.12
1. Obtain the execution result of a linux Command. For example, obtain the process tree structure of a PID. the linux Command is pstree-p pid, which can be easily obtained by a module in python. As for the case where the obtained results are garbled sometimes, please refer to the previous article: some commonly used commands in ubuntu
Command iscommands.
getoutput
(Cmd),
cmd = "pstree -p %s"%pidresult = commands.getoutput(cmd)
2. Start a new process to execute the script file. You need to use another module in python. subprocess
Next, let's briefly describe the functions.
1subprocess.
call
(Args,*,Stdin = None,Stdout = None,Stderr = None,Shell = False) The Calling process will wait until the sub-process executes the args and then return the returncode.
2subprocess.
check_output
(Args,*,Stdin = None,Stderr = None,Shell = False,Universal_newlines = False) The Calling process waits for the sub-process to execute args and returns its output in byte string format. NOTE: If return code is a non-zero value,CalledProcessError exception,
To call commands in the form of sub-processes, you need to use the Popen 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)
By default, a sub-process is opened and is not blocked.