Python uses Subprocess's popen to invoke system commands

Source: Internet
Author: User
Tags stdin

When we need to call the system's command, the first thing to consider is the OS module. Use Os.system () and Os.popen () to operate. 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. In this case, the Popen command in Subprocess will be able to perform the operation we need effectively. Here is a brief introduction to Popen.

Here is a very simple example, from the official website of Python tutorial: http://docs.python.org/library/subprocess.html

>>>ImportShlex,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 functions 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)

The parameter args can be a string or sequence type (for example: list, tuple) that specifies the process's executable file and its arguments. 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 child process by calling CreateProcess (), CreateProcess receives a string parameter, and if args is a sequence type, the system will pass List2cmdline () The function converts a sequence type to a string.

Parameter bufsize: If the bufsize parameter is specified the function is the same as the built-in function open (): 0 for non-buffering, 1 for row buffering, other positive for approximate buffer bytes, negative table
Use the system default values. The default is 0.


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 stdin, stdout, or stderr parameters. Represents a standard stream that communicates with a 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.

Here is a very simple example of 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 ')   print p.stdout.read ()   

#--Results--
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 child process finishes running and returns the ReturnCode of the process. The first example of this article demonstrates the call function. You can 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 only if the child process returns a returncode that 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, there are examples of how to use subprocess to replace some old modules with old ones. Interested friends can take a look.

Python uses Subprocess's popen to invoke system commands

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.