3 ways to execute DOS commands in Python summary __python

Source: Internet
Author: User
Tags stdin

1. Use Os.system ("cmd")

The feature is the execution of the program will play CMD on Linux implementation of the information.

Import OS

Os.system ("LS")


2. Use Popen module to generate new process

Now most people 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. Prior to use require from subprocess import Popen, PIPE. But the Popen function has a flaw, that is, it is a blocking method. If you run cmd with a lot of content, the function is very easy to block. The workaround is to not use the wait () method, but you cannot get the return value that was executed.

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, Cwd=none, Env=none, Universal_newlines=false, Startupinfo=none, creationflags=0)

Parameter bufsize: Specifies buffering.

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

Parameter stdin, stdout, stderr represents the standard input, output, and error handle of the program respectively. They can be pipe, file descriptors or file objects, or set to none to represent inheritance from the parent process.

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

Parameter CLOSE_SFS: Under the Windows platform, if the Close_fds is set to true, the newly created child process will not inherit the parent process's input, output, and error pipes. We cannot set Close_fds to true while redirecting standard input, output, and errors (stdin, stdout, stderr) of the subprocess.

If the argument shell is set to True, the program is executed through the shell.

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

The parameter env is a dictionary type that specifies the environment variable for the child process. If env = None, the child process's environment variable inherits from the parent process.

Parameter universal_newlines: Under different operating systems, text line breaks are not the same. For example: Windows uses '/r/n ' to change, while Linux uses '/n '. If this parameter is set to True,python unify these line breaks as '/n ' to be treated.

Parameter Startupinfo and createionflags are only used under Windows, and they are passed to the underlying CreateProcess () function to set some of the 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 stdin, stdout, or stderr parameters, representing the standard stream that communicates with the child process.

Subprocess. STDOUT

When the Popen object is created, it is used to initialize the stderr parameter, indicating that the error is output through the standard output stream.

The Popen method:

Popen.poll ()

Used to check whether the child process has ended. Sets and returns the ReturnCode property.

Popen.wait ()

Wait for child process to end. Sets and returns the ReturnCode property.

Popen.communicate (Input=none)

Interacts with a child process. Send data to stdin, or read data from stdout and stderr. Optional parameter input Specifies the parameters to be sent to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: If you want to send data to it through stdin of the process, 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 the STDOUT and stderr to pipe.

Popen.send_signal (signal)

Sends a signal to a child process.

Popen.terminate ()

Stops the child process (stop). Under Windows platform, this method calls the Windows API terminateprocess () to end the subprocess.

Popen.kill ()

Kill the child process.

Popen.stdin

If the Popen object is created, the parameter stdin is set to Pipe,popen.stdin will return a file object for the subprocess to send instructions. Otherwise, none is returned.

Popen.stdout

If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the subprocess to send instructions. Otherwise, None is returned.

Popen.stderr

If the Popen object is created, the parameter stdout is set to Pipe,popen.stdout will return a file object for the subprocess 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. Returns none if the process is not yet finished.

For example:

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

P.wait ()

If P.returncode!= 0:

Print "Error."

Return-1


3. Using the Commands.getstatusoutput method

This method also does not print out the information that CMD performs on Linux. The only advantage of this method is that it is not a blocking method. That is, there is no problem with popen function blocking. 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")

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: info-contact@alibabacloud.com 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.