Python invokes the system command with subprocess Popen __python

Source: Internet
Author: User
Tags stdin

The first OS module to consider when we need to call the system's commands. Operate with Os.system () and Os.popen (). However, these two commands are too simple to perform complex operations, such as providing input to a running command or reading the output of a command, judging the running state of the command, managing the parallelism of multiple commands, and so on. At this point, the Popen command in subprocess can effectively complete the operation we need. Here is a brief introduction to Popen.

The following is a very simple example 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 constructor is as follows:

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 args can be either a string or a sequence type (such as a list, a tuple) that specifies the executable file for the process and its parameters. If it is a sequence type, the first element is usually the path to the executable 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 subprocess by calling CreateProcess (), CreateProcess receives a string parameter, and if args is a sequence type, the system passes List2cmdline () function converts a sequence type to a string.

Parameter bufsize: Specifies buffering. I still do not know the specific meaning of this parameter, look at each Daniel pointing.


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. Represents a standard stream that communicates with a 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.

The following is a very simple example of how the Supprocess module interacts with a control console 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 ')
Print P.stdout.read ()

#--Result--
Input x:
Input y:
3 + 4 = 7

App2.exe is also a very simple console program that receives two values from the interface, performs a plus operation, 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)
Run the command. The function waits until the end of the child process runs and returns the ReturnCode of the process. The first example of the article demonstrates the call function. This function can be used to create a child process if it does not need to interact.

Subprocess.check_call (*popenargs, **kwargs)
As with the Subprocess.call (*popenargs, **kwargs) feature, a Calledprocesserror exception is triggered if the ReturnCode returned by a subprocess 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, it also describes how to use subprocess to replace some old modules, examples of old functions. Interested friends can have a look.

Reference Documentation:

Subprocess-subprocess Management

Pymotw:subprocess

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

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: 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.