Python uses the popen of subprocess to call system commands

Source: Internet
Author: User

When we need to call system commands, we should first consider the OS module. Use OS. System () and OS. popen () for operations. However, these two commands are too simple to complete complex operations, such as providing input or reading command output for running commands to determine the running status of the commands, manages parallel execution of multiple commands. In this case, the popen command in subprocess can effectively complete the operations we need. Here we will give a brief introduction to popen.

Below is a very simple example from Python official Tutorials: 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 has the following constructor functions:

 

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 args parameter can be a string or a sequence type (such as list and tuples). It is used to specify the executable file of a process and its parameters. For the sequence type, the first element is usually the path of the executable file. You can also explicitly use the executeable parameter to specify the path of the executable file. In Windows, popen creates a sub-process by calling CreateProcess (). CreateProcess receives a string parameter. If ARGs is of the sequence type, the system uses list2cmdline () the function converts the sequence type to a string.

Bufsize: Specify the buffer. I still don't know the specific meaning of this parameter. I hope you can give me some advice.


Executable is used to specify the executable program. Generally, the ARGs parameter is used to set the program to run. If the shell parameter is set to true, executable specifies the shell used by the program. On Windows, the default shell is specified by the comspec environment variable.


The stdin, stdout, and stderr parameters respectively indicate the standard input, output, and error handle of the program. They can be pipe, file descriptor or file object, or set to none, indicating that they are inherited from the parent process.


The preexec_fn parameter is valid only on the UNIX platform and is used to specify a callable object, which will be called before the sub-process runs.


Close_sfs: On Windows, if close_fds is set to true, the newly created child process does not inherit the input, output, and error channels of the parent process. We cannot set close_fds to true and redirect the standard input, output, and error (stdin, stdout, stderr) of the sub-process ).


If the shell parameter is set to true, the program will execute it through shell.


The CWD parameter is used to set the current directory of the sub-process.


The env parameter is a dictionary type used to indicate the environment variables of the child process. If Env = none, the environment variables of the child process are inherited from the parent process.


Universal_newlines: The text line breaks vary with operating systems. For example, in windows, '/R/N' is used, while in Linux,'/N' is used '. If this parameter is set to true, Python treats these linefeeds as '/N.


The startupinfo and createionflags parameters are valid only in windows. They are passed to the underlying CreateProcess () function and used to set attributes of sub-processes, such as the appearance of the main window, process Priority.

Subprocess. Pipe
When creating a popen object, subprocess. pipe can initialize the stdin, stdout, or stderr parameters. Indicates the standard stream that communicates with the sub-process.

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

Popen method:

Popen. Poll ()
Used to check whether the sub-process has ended. Set and return the returncode attribute.

Popen. Wait ()
Wait until the child process ends. Set and return the returncode attribute.

Popen. Communicate (input = none)
Interacts with sub-processes. Send data to stdin or read data from stdout and stderr. Optional parameter input specifies the parameter sent to the sub-process. Communicate () returns a tuples (stdoutdata, stderrdata ). Note: If you want to send data to the process through stdin, The stdin parameter must be set to pipe when you create a popen object. Similarly, if you want to obtain data from stdout and stderr, you must set stdout and stderr to pipe.

Popen. send_signal (signal)
Sends signals to sub-processes.

Popen. Terminate ()
Stop the sub-process. On Windows, this method calls the Windows API terminateprocess () to end the child process.

Popen. Kill ()
Kill the child process.

Popen. stdin
If the popen object is created, the stdin parameter is set to pipe, and popen. stdin returns a file object used to send commands by sub-processes. Otherwise, none is returned.

Popen. stdout
If the popen object is created, the stdout parameter is set to pipe, and popen. stdout returns a file object used to send commands by sub-processes. Otherwise, none is returned.

Popen. stderr
If the popen object is created, the stdout parameter is set to pipe, and popen. stdout returns a file object used to send commands by sub-processes. Otherwise, none is returned.

Popen. PID
Obtain the ID of the sub-process.

Popen. returncode
Obtain the return value of a process. If the process has not ended, none is returned.

The following is a simple example to demonstrate how the supprocess module interacts with a control platform 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. It receives two values from the interface, performs the add operation, and prints the result 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 some functions for you to create a process.

Subprocess. Call (* popenargs, ** kwargs)
Run the command. This function waits until the sub-process finishes running and returns the returncode of the process. The example at the beginning demonstrates the call function. This function can be used to create a child process without intercommunication.

Subprocess. check_call (* popenargs, ** kwargs)
Similar to the subprocess. Call (* popenargs, ** kwargs) function, a calledprocesserror exception is triggered if the returncode returned by the child process is not 0. The exception object contains the returncode information of the process.

There is so much content in the subprocess module. The Python Manual also describes how to use subprocess to replace some old modules and functions. If you are interested, you can take a look.

Reference:

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.