Python_cmd of various methods and advantages and disadvantages (subprocess. Popen, Os.system and Commands.getstatusoutput)

Source: Internet
Author: User
Tags deprecated

36.16.commands-utilities for runningcommands

Deprecated since version 2.6:the commands module has been removed in Python 3. Use the subprocess module instead.

The commands module contains wrapper functions for Os.popen () which take a system command as a string an D return any output generated by the command and, optionally, the exit status.

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results. Using the subprocess module is a preferable to using the commands module.

Note

In Python 3.x, GetStatus () and undocumented functions (Mk2arg ( ) and Mkarg ()) has been Remo Ved. Also, getstatusoutput () and getoutput () has been moved to the subprocess module.

The commands module defines the following functions:

commands. getstatusoutput ( cmd )

Execute the string  cmd  in a shell with  os.popen ()  and return a 2-tuple  (Status,  Output) .    cmd  is actually run as < Span class= "Pre" >{ cmd ; }  2>&1 , so, the returned output would contain output or error messages. A trailing newline is stripped from the output. The exit status for the command can is interpreted according to the rules for the C function wait () .

commands.< /span> getoutput ( cmd )

like  ; getstatusoutput () , except the exit The status is ignored and the return value is a string containing the command ' s output.

commands. GetStatus ( file )

Return the output of ls -ld file as a string. This function uses the getoutput () function, and properly escapes backslashes and dollar signs in the argument.

Deprecated since version 2.6:this function is nonobvious and useless. The name is also misleading in the presence of getstatusoutput ().

Example:

>>>
>>>ImportCommands>>>Commands.Getstatusoutput(' Ls/bin/ls ')(0, '/bin/ls ')>>>Commands.Getstatusoutput(' Cat/bin/junk ') >>> span class= "n" >commands. Getstatusoutput ( '/bin/junk ' )  (p, ' SH:/bin/ Junk:not found ') >>> commands . getoutput ( ' ls/bin/ls ' ) /bin/ ls ' >>> commands. Getstatus ( '/bin/ls ' )  '-rwxr-xr-x 1 root 13352 Oct 1994/bin/ls '              

See Also

Module subprocess
Module for spawning and managing subprocesses.
  Python_cmd of various methods and advantages and disadvantages (subprocess. Popen, Os.system and Commands.getstatusoutput) Category: Linux program2014-07-08 15:50 1069 people read reviews (0) favorite reports

Transferred from: http://blog.csdn.net/menglei8625/article/details/7494094

Refer:https://docs.python.org/2/library/commands.html?highlight=commands#commands

There are currently three ways to execute cmd in the python I use:

1. Using Os.system ("cmd")

This is the simplest method, characterized by the execution of the program will play CMD on Linux execution information. Import OS required before use.

[Python]
    1. 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:

[Python]
    1. 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. I still do not know the specific meaning of this parameter, look at each Daniel pointing.

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.

Popen.stdin
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.

Popen.stdout
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.

Popen.stderr
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.

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 finished yet.


For example:

[Python]
    1. p = Popen ("CP-RF a/* b/", Shell=True, Stdout=pipe, stderr=pipe)
    2. P.wait ()
    3. If P.returncode! = 0:
    4. print "Error."
    5. return-1

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:

[Python]
    1. Status, Output = Commands.getstatusoutput ("ls")

There are also ways to get output and status only: [Python]
    1. Commands.getoutput ("ls")
    2. Commands.getstatus ("ls")

Python_cmd of various methods and advantages and disadvantages (subprocess. Popen, Os.system and Commands.getstatusoutput)

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.