Execute system command
The relevant modules and functions that can execute shell commands are:
- Os.system
- os.spawn*
- os.popen*--Waste
- popen2.*--Waste
- commands.*-Discarded, removed in 3.x
1 Import commands 2 3 result = Commands.getoutput ('cmd')4 result = Commands.getstatus ('cmd')5 result = Commands.getstatusoutput ('cmd')
commands
The functions of the relevant modules and functions for executing shell commands are implemented in the Subprocess module and provide richer functionality.
Pager
Execute command, return status code
ret = Subprocess.call (["LS", "-l"], shell=false) ret = Subprocess.call ("Ls-l", Shell=true)
shell = True, allowing shell commands to be in string form
Check_call
Executes the command, returns 0 if the execution status code is 0, or throws an exception
Subprocess.check_call (["LS", "-l"]) Subprocess.check_call ("Exit 1", shell=true)
Check_output
Executes the command, if the status code is 0, returns the execution result, otherwise throws an exception
Subprocess.check_output (["echo", "Hello world!"]) Subprocess.check_output ("Exit 1", shell=true)
Subprocess. Popen (...)
Used to perform complex system commands
Parameters:
- The Args:shell command, which can be a string or sequence type (for example: list, tuple)
- BufSize: Specifies buffering. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering
- stdin, stdout, stderr: Indicates the standard input, output, and error handles of the program, respectively
- PREEXEC_FN: Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run
- CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process.
- Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process.
- Shell: Ibid.
- CWD: Used to set the current directory of child processes
- ENV: The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.
- Universal_newlines: Different system line breaks differ, True----agree to use \ n
- Startupinfo and Createionflags are only valid under Windows
- will be passed to the underlying CreateProcess () function to set some properties of the child process, such as: the appearance of the main window, the priority of the process, etc.
1 Import subprocess 2 ret1 = subprocess. Popen (["mkdir","T1"])3 Ret2 = Subprocess. Popen ("mkdir T2", Shell=true)
Execute common Commands
The commands for terminal input are divided into two types:
- Input can be output, such as: ifconfig
- Input to an environment that relies on re-entry, such as: Python
Import= subprocess. Popen ("mkdir T3", Shell=true, cwd='/home/dev',)
View Code
ImportSubprocessobj= subprocess. Popen (["python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, stderr=subprocess. PIPE) Obj.stdin.write ('print 1 \ n') Obj.stdin.write ('Print 2 \ n') Obj.stdin.write ('Print 3 \ n') Obj.stdin.write ('Print 4 \ n') obj.stdin.close () Cmd_out=Obj.stdout.read () obj.stdout.close () Cmd_error=Obj.stderr.read () obj.stderr.close ( )PrintCmd_outPrintCmd_errorView Code
ImportSubprocessobj= subprocess. Popen (["python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, stderr=subprocess. PIPE) Obj.stdin.write ('print 1 \ n') Obj.stdin.write ('Print 2 \ n') Obj.stdin.write ('Print 3 \ n') Obj.stdin.write ('Print 4 \ n') Out_error_list=obj.communicate ()PrintOut_error_listView Code
Import= subprocess. Popen (["python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, stderr== obj.communicate ('print ' Hello')print out_ Error_list
View Code
More Punch here
---------------------------------------------------------------
subprocessthe module allows spawn new processes, connect to their input/output/error pipes, and obtain their return cod Es. This module intends to replace several older modules and functions:
Os. SystemOS. Spawn*
The recommended approach to invoking subprocesses are to use the function for all use run() cases it can handle. For cases, the underlying Popen interface can is used directly.
run()The function is added in Python 3.5; If you need to retain compatibility with older versions, see the older High-le Vel API section.
subprocess.run(args, *, stdin=none, input=none, stdout=none, stderr= None, shell=false, timeout=none, check=false)
Run the command described by args. Wait for command to complete and then return a CompletedProcess instance.
The arguments shown above is merely the most common ones, described below in frequently used arguments (hence the use of Keyword-only notation in the abbreviated signature). The full function signature Popen are largely the same as that of the Constructor-apart from timeout, input< /c4> and check, the arguments to this function is passed through to that interface.
This does is not a capture stdout or stderr by default. To does so, pass for the PIPE stdout and/or stderr arguments.
The Timeout argument is passed to Popen.communicate() . If The timeout expires, the child process is killed and waited for. The exception'll is re-raised after the child TimeoutExpired process has terminated.
The Input argument is passed to and thus to the Popen.communicate() subprocess ' s stdin. If used it must be a byte sequence, or a string if universal_newlines=True . When used, the internal Popen object was automatically created stdin=PIPE with, and the stdin argument could not be used a s well.
If Check is True, and the process exits with a Non-zero exit code, a CalledProcessError exception would be raised. Attributes of that exception hold the arguments, the exit code, and stdout and stderr if they were captured.
>>> subprocess.run (["LS", "-l"]) # doesn ' t capture outputcompletedprocess (args=[' ls ', '-l '], returncode= 0) >>> Subprocess.run ("Exit 1", Shell=true, Check=true) Traceback (most recent call last): ... subprocess. Calledprocesserror:command ' exit 1 ' returned Non-zero exit status 1 >>> subprocess.run (["LS", "-L", "/dev/null"] , Stdout=subprocess. PIPE) completedprocess (args=[' ls ', '-l ', '/dev/null '), returncode=0,stdout=b ' crw-rw-rw-1 root root 1, 3 Jan 16:23/dev/ Null\n ')
Call Subprocess.run (...) Is the recommended common method, in most cases it satisfies the requirements, but if you may need to do some complex interaction with the system, you can also use subprocess. Popen (), the syntax is as follows:
p = subprocess. Popen ("Find/-size +1000000-exec LS-SHL {} \;", shell=true,stdout=subprocess. PIPE) Print (P.stdout.read ())
Available parameters:
- The Args:shell command, which can be a string or sequence type (for example: list, tuple)
- BufSize: Specifies buffering. 0 unbuffered, 1 row buffer, other buffer size, negative system buffering
- stdin, stdout, stderr: Indicates the standard input, output, and error handles of the program, respectively
- PREEXEC_FN: Valid only on UNIX platforms, specifying an executable object (callable object) that will be called before the child process is run
- CLOSE_SFS: Under the Windows platform, if Close_fds is set to true, the newly created child process will not inherit the input, output, and error pipes of the parent process.
Therefore, you cannot set Close_fds to true while redirecting the standard input, output, and error (stdin, stdout, stderr) of the child process.
- Shell: Ibid.
- CWD: Used to set the current directory of child processes
- ENV: The environment variable used to specify the child process. If env = None, the environment variables of the child process are inherited from the parent process.
- Universal_newlines: Different system line breaks differ, True----agree to use \ n
- Startupinfo and Createionflags are only valid under Windows
will be passed to the underlying CreateProcess () function to set some properties of the child process, such as: the appearance of the main window, the priority of the process, etc.
The commands for terminal input are divided into two types:
- Input can be output, such as: ifconfig
- Input to an environment that relies on re-entry, such as: Python
Examples of commands that require interaction
Import subprocess obj = subprocess. Popen (["Python"], stdin=subprocess. PIPE, Stdout=subprocess. PIPE, Stderr=subprocess. PIPE) Obj.stdin.write (' Print 1 \ n ') obj.stdin.write (' Print 2 \ n ') obj.stdin.write (' Print 3 \ n ') obj.stdin.write (' Print 4 \ n ') out_error_list = Obj.communicate (timeout=10) Print out_error_list
Python Learning Notes-basic "Sixth Week"--subprocess module