Detailed explanation of three methods of calling cmd command by python

  • 2021-07-10 20:26:18
  • OfStack

At present, there are three ways to execute cmd in python that I use

Use os. system ("cmd")

After calling shell script, the method returns a 16-bit binary number, the low bit is the signal number that kills the called script, and the high bit is the exit status code of the script, that is, after the code of "exit 1" in the script is executed, the high bit of the return value of os. system function is 1, and if the low bit number is 0, the return value of the function is 0 × 100, which is converted into decimal to get 256.

If we need to get the correct return value of os. system, we can restore the return value by using displacement operation:


>>> n = os.system(test.sh)
>>> n >> 8
>>> 3

This is the simplest method, which is characterized by the information that cmd executes on linux when executing. import os is required before use.

os. system ("ls") only runs system commands on one sub-terminal, and cannot obtain the return information after command execution

os.Popen

This call mode is realized by pipeline. The function returns an file-like object, and the content inside is the content of script output (which can be simply understood as the content of echo output). Calling test. sh with os. popen: python calls the Shell script in two ways: os. system (cmd) or os. popen (cmd), with the return value of the former being the exit status code of the script and the return value of the latter being the output during script execution. In actual use, it is selected according to the demand. Obviously, an shell command such as calling "ls" should use the method of popen to get the content


popen(command [, mode='r' [, bufsize]]) -> pipe
tmp = os.popen('ls *.py').readlines()

subprocess.Popen

Nowadays, most people like to use Popen. The Popen method does not print the information that cmd executes on linux. Indeed, Popen is very powerful and supports many parameters and modes. from subprocess import Popen and PIPE are required before use. However, the Popen function has one defect, that is, it is a blocking method. If there is a lot of content generated when running cmd, the function is very easy to block. The workaround is not to use the wait () method, but you can't get the return value of the execution.

The Popen prototype is:

subprocess.Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=false)

Parameter bufsize: Specifies buffering. I still don't know the specific meaning of this parameter, so I hope every big cow can give me some advice.

The parameter executable is used to specify the executable program. 1 In general, we set the program to be run through args parameters. If the parameter shell is set to True, executable specifies the shell used by the program. Under the windows platform, the default shell is specified by the COMSPEC environment variable.

Parameters stdin, stdout and stderr represent the standard input, output and error handles of the program respectively. They can be PIPE, file descriptors, or file objects, or they can be set to None to indicate inheritance from the parent process.

The parameter preexec_fn is valid only under the Unix platform and specifies one executable object (callable object) that will be called before the child process runs.

Parameter Close_sfs: Under windows, 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. We cannot set close_fds to True and redirect the standard input, output, and error of the child process (stdin, stdout, stderr).

If the parameter shell is set to true, the program will be executed through shell.

Parameter cwd is used to set the current directory of the child process.

Parameter env is a dictionary type, which specifies the environment variable of the child process. If env = None, the environment variables of the child process are inherited from the parent process.

Parameter Universal_newlines: Under different operating systems, the newline character of text is different. For example, '/r/n' is used under windows, and '/n' is used under Linux. If this parameter is set to True, Python 1 treats these newlines as'/n '.

Parameters startupinfo and createionflags are used only under windows, and they are passed to the underlying CreateProcess () function, which is used to set some properties of the child process, such as the appearance of the main window, the priority of the process, and so on.

subprocess.PIPE
When an Popen object is created, subprocess. PIPE can initialize stdin, stdout, or stderr parameters that represent a standard stream of communication with child processes.

subprocess.STDOUT
When an Popen object is created, it is used to initialize the stderr parameter, indicating that errors are output through the standard output stream.

Method of Popen:

Popen.poll()
Used to check whether the child process has ended. Sets and returns the returncode property.

Popen.wait()
Wait for the child process to end. Sets and returns the returncode property.

Popen.communicate(input=None)
Interact with child processes. Send data to stdin or read data from stdout and stderr. The optional parameter input specifies the parameters sent to the child process. Communicate () returns 1 tuple: (stdoutdata, stderrdata). Note: If you want to send data to a process via its stdin, the parameter stdin must be set to PIPE when creating an Popen object. Similarly, if you want to get data from stdout and stderr, you must set stdout and stderr to PIPE.

Popen.send_signal(signal)
Send a signal to the child process.

Popen.terminate()
Stop (stop) child process. Under the windows platform, this method calls Windows API TerminateProcess () to end the child process.

Popen.kill()
Kill the child process.

Popen.stdin
If the Popen object is created and the parameter stdin is set to PIPE, Popen. stdin will return 1 file object for the child process to send instructions. Otherwise None is returned.

Popen.stdout
If the Popen object is created and the parameter stdout is set to PIPE, Popen. stdout will return 1 file object for the child process to send instructions. Otherwise None is returned.

Popen.stderr

If the parameter stdout is set to PIPE after creating the Popen object, Popen. stdout will return 1 file object for the child process to send instructions. Otherwise None is returned.

Popen.pid
Gets the process ID of the child process.

Popen.returncode
Gets the return value of the process. If the process is not finished, return None.

Example 1


p = Popen("cp -rf a/* b/", shell=True, stdout=PIPE, stderr=PIPE) 
p.wait() 
if p.returncode != 0: 
 print "Error." 
 return -1 

Use the commands. getstatusoutput method

This method also does not print out the information that cmd executes on linux. The only advantage of this method is that it is not a blocking method. That is, there is no problem of Popen function blocking. import commands is required before use.

For example


 status, output = commands.getstatusoutput("ls") 
  And only get output And status Method of: 
 commands.getoutput("ls") 
 commands.getstatus("ls")

Related articles: