Summarize several methods of executing commands in Python

Source: Internet
Author: User
There are currently three ways to execute cmd in the python I use:

1. Using Os.system ("cmd")

The feature is that when executed, the program will play CMD on Linux execution information.

Import OS

Os.system ("LS")

2. Using the Popen module to generate a new process

Most people now like to use Popen. The Popen method does not print out the information that CMD executes on Linux. Indeed, Popen is very powerful and supports a variety of parameters and patterns. Need from subprocess import Popen, PIPE before use. But there is a flaw in the Popen function, which is that it is a blocking method. If there is a lot of content generated when you run CMD, the function is very easy to block. The workaround is not to use the wait () method, but you cannot get the return value of the execution.

Popen prototypes are:

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)

Parameter bufsize: Specifies the buffer.

The parameter executable is used to specify the executable program. In general, we use the args parameter to set the program to run. If you set the parameter shell to true,executable, the shell will be used by the specified program. Under the Windows platform, the default shell is specified by the COMSPEC environment variable.

The parameters stdin, stdout, stderr respectively represent the standard input, output, and error handles of the program. They can be pipe, file descriptor or file object, or set to none, which means inheriting from the parent process.

The parameter PREEXEC_FN is only valid on UNIX platforms and is used to specify an executable object (callable object) that will be called before the child process runs.

Parameter 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. We cannot set Close_fds to true while redirecting standard input, output, and error (stdin, stdout, stderr) of child processes.

If the parameter shell is set to True, the program executes through the shell.

The parameter CWD is used to set the current directory of the child process.

The parameter env is a dictionary type that specifies the environment variables for 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, text line breaks are not the same. such as: Under Windows with '/r/n ' for Exchange, and Linux under the '/n '. If this parameter is set to True,python uniform, these newline characters are treated as '/n '.

Parameters Startupinfo and Createionflags are only used under Windows, and they are 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, and so on.

Subprocess. PIPE

When you create a Popen object, subprocess. Pipe can initialize the stdin, stdout, or stderr parameters, representing the standard flow of communication with the child process.

Subprocess. STDOUT

When you create a Popen object, the stderr parameter is initialized to indicate that the error is output through the standard output stream.

Methods 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)

Interacts with the child process. Send data to stdin, or read data from stdout and stderr. Optional parameter input Specifies the parameters that are sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to send data to it through the process's stdin, the parameter stdin must be set to pipe when the Popen object is created. Similarly, if you want to get data from stdout and stderr, you must set stdout and stderr to pipe.

Popen.send_signal (signal)

Sends a signal to a child process.

Popen.terminate ()

Stop (stop) child process. Under the Windows platform, this method will call Windows API TerminateProcess () to end the child process.

Popen.kill ()

Kills a child process.


If the Popen object is created, the parameter stdin is set to Pipe,popen.stdin will return a file object for the policy child process send instruction. Otherwise, none is returned.


If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, None is returned.


If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the policy child process send instruction. Otherwise, None is returned.

Gets the process ID of the child process.


Gets the return value of the process. Returns none if the process is not finished yet.

For example:

p = Popen ("cp-rf a/* b/", Shell=true, Stdout=pipe, Stderr=pipe)

P.wait ()

If P.returncode! = 0:

Print "Error."


3. Using 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 popen function blocking problem. Import commands is required before use.

For example:

Status, Output = Commands.getstatusoutput ("ls")

There are also ways to get output and status only:

Commands.getoutput ("LS")

Commands.getstatus ("LS")

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.