Python uses Subprocess's popen to invoke system commands

Source: Internet
Author: User

The OS module that is first considered when we need to invoke the command of the system. Use Os.system () and Os.popen () to operate. However, these two commands are too simple to complete a complex operation, such as providing input to the executed command or reading the output of the command, inferring the execution state of the command, managing the parallelism of multiple commands, and so on. At this time the Popen command in the subprocess can effectively complete the operation we need. Here is a brief introduction to Popen.

here is a very easy sample, from the official website of Python tutorial: http://docs.python.org/library/subprocess.html

>>>Import Shlex, subprocess>>>Command_line = Raw_input()/bin/vikings-input eggs.txt-output "spam spam.txt"-cmd "Echo ' $MONEY '">>>args = Shlex.Split(Command_line)>>>Print args['/bin/vikings ', '-input ', ' eggs.txt ', '-output ', ' spam spam.txt ', '-cmd ', ' echo ' $MONEY ']>>>P = subprocess.Popen(args) # success!

Popen its constructors such as the following:

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)

number of parameters args can be a string or sequence type (for example: list, tuple) that specifies the executable file and its parameters of the process. A sequence type is assumed, and the first element is typically the path to a running file. We can also explicitly use the executeable parameter to specify the path to the executable file. On the Windows operating system, Popen creates a child process by calling CreateProcess (), CreateProcess receives a string parameter, assuming that args is a sequence type, the system will pass List2cmdline () The function converts a sequence type to a string.

Parameter bufsize: Specifies the buffer. I still do not know the detailed meaning of this reference, looking at the various Daniel pointing.


The parameter executable is used to specify the executable program. In general, we use the args parameter to set the program to be executed. Suppose you set the reference 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.


The stdin, stdout, stderr represent the standard input, output, and error handles of the program, respectively. They can be pipes, file descriptive descriptors or file objects, and can be set to none, which means inheriting from the parent process.


The 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 executes.


Number of CLOSE_SFS: Under the Windows platform, assuming that 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 to redirect the standard input, output, and error (stdin, stdout, stderr) of the child process at the same time.


Assuming that the parameter shell is set to True, the program will run through the shell.


Parameter CWD sets the current folder for the child process.


Argument env is a dictionary type that specifies the environment variables for a child process. Assuming env = None, the environment variables for the child process are inherited from the parent process.


Number of Universal_newlines: Different operating systems, text line breaks are not the same. such as: Under Windows with '/r/n ' for Exchange, and Linux under the '/n '. Assume that this parameter is set to True,python uniform to treat these newline characters as '/n '.


The Startupinfo and createionflags are only valid under Windows, and they are passed to the underlying CreateProcess () function, which sets some properties of the child process, such as the appearance of the main form, 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. Represents a standard stream that communicates with a child process.

Subprocess. STDOUT
When you create an Popen object, the stderr parameter is used to initialize the error to 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 number of parameters to send to the child process. Communicate () returns a tuple: (Stdoutdata, Stderrdata). Note: Suppose you want to send data to it through the stdin of the process, and when you create the Popen object, the parameter stdin must be set to pipe. 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
Assuming that 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
Assuming that 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
Assuming that 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. Assuming that the process has not ended, return none.

Here is a very easy sample to demonstrate how the Supprocess module interacts with a control-desk application.

import SUBPROCESS   

p = subprocess. Popen ("App2.exe", stdin = subprocess. PIPE,/   
stdout = subprocess. PIPE, stderr = subprocess. PIPE, Shell = False)    

P.stdin.write (' 3/n ')    
p.stdin.write (' 4/n ')    < BR style= "Line-height:normal;" >print p.stdout.read ()    

#--results --&NBSP;&NBSP;&NBSP;
input x:    
input y:    
3 + 4 = 7 < BR style= "Line-height:normal;" >

App2.exe is also a very easy console program that receives two values from the interface, runs plus operations, and prints the results to the console. The code is as follows:

#include <iostream>
using namespace Std;

int main (int argc, const char *artv[])
{
int x, y;
cout << "input x:" << Endl;
CIN >> X;
cout << "Input y:" << Endl;
Cin >> y;
cout << x << "+" << y << "=" << x + y << Endl;

return 0;
}

The Supprocess module provides functions that allow us to create processes.

Subprocess.call (*popenargs, **kwargs)
Executes the command. The function waits until the child process finishes executing and returns the ReturnCode of the process. The example at the beginning of the article demonstrates the call function. It is possible to use this function to create a child process if it does not need to interact.

Subprocess.check_call (*popenargs, **kwargs)
As with Subprocess.call (*popenargs, **kwargs), the calledprocesserror exception is triggered simply by assuming that the ReturnCode returned by the child process is not 0. In the exception object, include the ReturnCode information for the process.

The subprocess module has so much content. In the Python manual, we also show you how to use subprocess to replace some old modules with old ones. Interested friends can take a look.

Documentation:

Subprocess-subprocess Management

Pymotw:subprocess

Http://hi.baidu.com/kobeantoni/blog/item/a034bce9d0e01bdfd539c9a4.html

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.