• Use the os.system() method

The os.system command is used to execute CMD commands. The output in CMD is directly output on the console.

Sample code:

# coding:utf-8

import os

os.system("ls")
Copy the code

The PS:os.system() method simply executes the CMD command, and there is no way to get the content of the CMD output.

The PPS:os.system() method returns a 16-bit binary number after calling the shell script. The low number is the signal number to kill the called script, and the high number is the exit status code of the script. That is, after the execution of the code “exit 1” in the script, the high number of the return value of the os.system function is 1. If the low order value is 0, the function returns 0x0100, which in decimal form yields 256.

  • Use the os.popen() method

The os.popen() method is used to open a pipe from a command. This works on Unix and Windows. Os.popen returns a file object, just as open does to open a file.

The popen() method has the following syntax:

os.popen(command[, mode[, bufsize]])
Copy the code

Parameters:

Command - The command to use. Mode - Mode permission can be 'R' (default) or 'W'. Bufsize - Specifies the buffer size required for the file: 0 means no buffer; 1 means row buffering; Other positive values indicate the buffer size (approximate value, in bytes) used for the parameter. Negative bufsize means using the system default, which is generally line buffering for TTY devices; For other files, it is fully buffered. If the parameters are not changed, use the default values.Copy the code

Sample code:

# coding:utf-8

import os

# popen returns a file object, just like the open operation
f = os.popen(r"ls"."r")

l = f.read()
print(l)
f.close()
Copy the code

The return value is the recommended handling of the file object:

with os.popen(cmd, "r") as p:
    r = p.read()
Copy the code

To use it, you don’t need to explicitly write p.close().

The PS: os.popen() method is non-blocking.

  • Use the subprocess. Popen ()

Python2.4 provides the subprocess module to generate a child process and to connect to its standard input, output, error, and return values.

Subprocess.popen () is defined as follows:

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)
Copy the code

The meaning of its parameters is not described here. A simple example of code:

# coding:utf-8

import subprocess

p = subprocess.Popen("ls", shell=True, stdout=subprocess.PIPE)
r = p.stdout.read()
print(r)
Copy the code

PS: Subprocess provides two method call subroutines. Subprocess.call () is blocking and subprocess.popen () is non-blocking.