Python calls external system commands

  Using Python to call external system commands can improve coding efficiency. After calling the external system command, you can obtain the command execution return result code and the execution output result for further processing. This article mainly describes the common methods of calling external system commands in Python, including os.system(), os.popen(), subprocess.Popen(), etc.

1. Subprocess module

  The priority to introduce the subprocess module is that this module can replace the methods of the old module, such as os.system(), os.popen(), etc. It is recommended to use it. The subporcess module can call external system commands to create new subprocesses, and can connect to the nput/output/error pipes of the subprocess, and get the return value of the subprocess. The subprocess module mainly includes call(), check_call(), check_output(), and Popen() functions, which are briefly described 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

  Let's start to introduce how to use the subprocess function.

  subprocess.Popen类

 Constructor: subprocess.Popen(args, stdin=None, stdout=None, stderr=None, shell=False) #Too many parameters, only key parameters are listed

 illustrate:

 (1) The args parameter is the external system command to be called.

 (2) When the shell parameter value is False, the corresponding program is executed on Linux by calling os.execvp. When it is Trule, the system shell is directly invoked on Linux to execute the program. On Windows, regardless of whether the shell is False or True, CreateProcess is called to execute the specified external program.

(3) stdin, stdout, and stdout are used to specify the standard input, standard output and standard error of the child process, respectively. Its value can be PIPE, file descriptor, None, etc. The default value is None.

  Examples of use are as follows:

import subprocess

p = subprocess.Popen(args='ping -n 2 -w 3 192.168.1.104',stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
p.wait()
print p.stdout.read()

  Description: After getting the output, p.stdout(<open file '<fdopen>', mode 'rb'>) becomes a readable file object, which can be read by using file operation functions.

subprocess.call()

  Function prototype: call(*popenargs, **kwargs). call() invokes external system command execution and returns the program execution result code.

 

import subprocess

retcode = subprocess.call('ping -n 2 -w 3 192.168.1.104', shell=True)
print retcode

 

subprocess.check_call()

   The usage method is the same as call(). If the call command is executed successfully, the result code 0 is returned. If the execution fails, the CalledProcessError. exception is thrown. An example is as follows:

 

>>> p = subprocess.check_call('ping -n 2 -w 3 192.168.1.105', shell=True)

Pinging 192.168.1.105 with 32 bytes of data:
Request timed out.
Request timed out.

Ping stats for 192.168.1.105 :
    Packets: Sent = 2, Received = 0, Lost = 2 (100% lost),
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\Python27\lib\subprocess.py", line 186, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'ping -n 2 -w 3 192.168.1.105' returned non-zero exit status 1

 subprocess.check_output()

  Function prototype: check_output(*popenargs, **kwargs). Usage is the same as call(). The difference is that if the execution is successful, the standard output content is returned. If it fails, throw CalledProcessError. exception.

import subprocess

output = subprocess.check_output('ping -n 2 -w 3 192.168.1.104', shell=True)
print output

2. os module

  os.system()

  os.system(command) . An external system command is called and the command result code is returned, but the command execution output result cannot be obtained.

import them

ip = '192.168.1.104'
ping_cmd  = 'ping -n 2 -w 3 %s > null' % (ip,)
retcode = os.system('ping -n 2 -w 3 192.168.1.104')
if retcode == 0:
    print "%s Success" % (ip,)
else:
    print "%s Fail" % (ip,)

os.popen()

os.popen(command) . Calling an external system command and returning the command execution output result, but not returning the result?

import them

ip = '192.168.1.104'
ping_cmd  = 'ping -n 2 -w 3 %s > null' % (ip,)
output = os.popen('ping -n 2 -w 3 192.168.1.104')
print output

3. Commands module

  The commands module mainly has the following three functions

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.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325160187&siteId=291194637