preamble
Using Python to call external system commands can improve coding efficiency. Calling external system commands can be further processed after the completion of the command execution by obtaining the command execution return result code, the output of the execution. This article mainly describes the common methods of calling external system commands in Python, including (), (), () and so on.
This article analyzes python call external system commands from two main considerations: 1, is it possible to return to the command execution result code, because most of the scenarios need to be called to determine whether the command is executed successfully or failed. 2, is it possible to get the results of the command execution. Some scenarios call the external command is to get the output, but also through the output to determine the success or failure of the command execution. Analyze the results as follows:
Each of these functions is described in more detail below, along with examples of how to use them.
1. subprocess module
Priority is given to the introduction of the subprocess module is due to the fact that this module can replace the methods of the old module, such as (), (), etc., it is recommended to use. subporcess module can call external system commands to create a new sub-process, and at the same time can be connected to the sub-process of the nput/output/error pipeline, and get the return value of the sub-process. subprocess module mainly has call(), check_call(), check_output(), Popen() function, a brief description is as follows:
Main API ======== call(...): Runs a command, waits for it to complete, then returns the return code. check_call(...): Same as call() but raises CalledProcessError() if return code is not 0 check_output(...): Same as check_call() but returns the contents of stdout instead of a return code Popen(...): A class for flexibly executing a command in a new process Constants --------- PIPE: Special value that indicates a pipe should be created STDOUT: Special value that indicates that stderr should go to stdout
The use of the subprocess function begins below.
(1) Class
(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)
Parameter Description:
args: External system commands to invoke。 bufsize: The default value is0, Indicates no caching,。because of1Indicates a line cache,。Other positive numbers indicate the size of the cache used,,negative number-1Indicates that the system default cache size is used。 stdin、stdout、stdout denote the standard inputs, respectively、Standard Output and Standard Errors。其值可以because ofPIPE、file descriptor andNoneet al. (and other authors)。The default value isNone,Indicates inheritance from the parent process。 shell Linux:参数值because ofFalsehour,LinuxThe corresponding program is executed by calling。because ofTrulehour,LinuxCalling the system directly on theshellto execute the program。 Windows:shellparameter indicates whether to use thebat作because of执行环境。Only implementationwindows(used form a nominal expression)dir、copyet al. (and other authors)命令hour才需要设置because ofTrue。No difference in other programs。 executable Used to specify an executable program。Normally we pass theargs参数来设置所要运行(used form a nominal expression)程序。If the parametershell设because of True,executable将指定程序使用(used form a nominal expression)shell。existwindowsoff-platform,默认(used form a nominal expression)shellleave it (to sb)COMSPECenvironment variable to specify the。 preexec_fn 只existUnixoff-platform有效,Used to specify an executable object(callable object),它将exist子进程运行之前被调用 cwd Setting the current directory of a child process env envis a dictionary type,用于指定子进程(used form a nominal expression)环境变量。The default value isNone,表示子进程(used form a nominal expression)环境变量将从父进程中继承。 Universal_newlines under different operating systems,文本(used form a nominal expression)换行符是不一样(used form a nominal expression)。as if:windowsunderneath'/r/n'denote,(indicates contrast)Linuxunderneath ‘/n'. If this parameter is set to True, Python uniformly treats these line breaks as '/n'handle。
The corresponding properties and methods of the Popen object are as follows:
causality: stdin, stdout, stderr, pid, returncode methodologies: communicate(self, input=None) -> returns a tuple (stdout, stderr). wait(self) -> Wait for child process to terminate. Returns returncode attribute.
Common Examples
1. Print D:\temp directory to create the test directory. Directly invoke the process, do not consider getting the output of the invocation command and result code
import subprocess p = (args='mkdir test', shell=True, cwd='d:/temp') ()
2. Call the ping command and get the output of the command.
import subprocess p = (args='ping -n 2 -w 3 192.168.1.104', stdin=, stdout=, stderr=, shell=True) () print ()
Description:,, for file objects, you can use file object functions such as read().
(2)()
Function prototype: call(*popenargs, **kwargs). call() calls the external system command execution and returns the program execution result code.
import subprocess retcode = ('ping -n 2 -w 3 192.168.1.104', shell=True) print retcode
(3)subprocess.check_call()
Used in the same way as call(). If the call command executes successfully, the result code 0 is returned, and if the execution fails, the CalledProcessError.exception is thrown. Examples are as follows:
>>> p = subprocess.check_call('ping -n 2 -w 3 192.168.1.105', shell=True) in the process of (doing something or happening) Ping 192.168.1.105 have 32 byte: Request timeout。 Request timeout。 192.168.1.105 (used form a nominal expression) Ping Statistical information: datagram: Sent = 2,Accepted = 0,loss = 2 (100% loss), Traceback (most recent call last): File "<stdin>", line 1, in <module> File "c:\Python27\lib\", line 186, in check_call raise CalledProcessError(retcode, cmd) : Command 'ping -n 2 -w 3 192.168.1.105' returned non-zero exit status 1
(4)subprocess.check_output()
Function prototype: check_output(*popenargs, **kwargs). Usage is the same as call(). The difference is that if the execution succeeds, the standard output is returned. If it fails, a CalledProcessError exception is thrown.
import subprocess output = subprocess.check_output('ping -n 2 -w 3 192.168.1.104', shell=True) print output
2. os module
(1)()
(command). Calls an external system command and returns the command result code, but cannot get the output of the command, which is printed directly to the screen terminal.
import os retcode = ('ping -n 2 -w 3 192.168.1.104') if retcode == 0: print "%s Success" % (ip,) else: print "%s Fail" % (ip,)
(2)()
(command). Calls an external system command and returns the output of the command execution, but not the result?
import os output = ('ping -n 2 -w 3 192.168.1.104') print output
3. commands module
The commands module is used to call Linux shell commands. I tested it and it fails on windows. There are 3 main functions as follows
getoutput(cmd): Return output (stdout or stderr) of executing cmd in a shell. getstatus(file):Return output of "ls -ld <file>" in a string. getstatusoutput(cmd):Return (status, output) of executing cmd in a shell
Examples of use are shown below:
import commands retcode, output = ('ping -n 2 -w 3 192.168.1.104') print retcode print output
summarize
When writing a program you can choose different Python invocation methods to execute external system commands according to the usage scenario. For complex commands consider using () to complete, if only a simple command execution, you can use () to complete, such as calling the windows pause program command ('pause').
This is the whole content of this article.