Zz:python subprocess Create Child process (open new CMD window under Windows) __python

Source: Internet
Author: User
Tags stdin python subprocess
ZZ from:http://www.cnblogs.com/oubo/archive/2011/10/10/2394593.html
Python subprocess Create child processes

Python provides multiple modules for creating child processes, and I am more accustomed to using the subprocess module because there is a phrase in the Python manual:

This module intends to replace several, older modules and functions, such as:os.system, os.spawn*, os.popen*, popen2.* , commands.*

Subprocess is used to replace some old modules and functions, such as: Os.system, os.spawn*, os.popen*, popen2.*, commands.*. Visible, subprocess is recommended for use in the module.

Module selection Comparison

1.os.system ()
Disadvantages:
A. Os.system () is a new shell to work, the cost of the system is relatively large
B. Getting output and other information is cumbersome and cannot be interacted with external commands or tools
C. Unable to control (if an external command is invoked, hangs or executes for a long time), the main process cannot control Os.system () because the calling Os.system (cmd) call process blocks, until Os.system () exits

2.commands
Advantages:
A. Easy to get output from external commands, exiting state
Disadvantages:
A,c in the same os.system ()

3.os.popen ()
Same Commands command

4.subprocess
Advantages:
A. Support and child process interaction
B. Support for synchronous/asynchronous execution of child processes
C. Can be child process communication
D. Customizable IO Pipelines
E. Can control whether to open a new shell work
.......
Subprocess. Popen

Only one class is defined in the Subprocess module: Popen. You can use Popen to create processes and have complex interactions with processes. 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 description: args: Can be a string or a sequence type (such as: list, tuple), to specify the process executable file 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. BufSize: Specifies buffering. It hasn't been used so far. Executable: Used to specify executable programs. 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. stdin, stdout, stderr represent 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. PREEXEC_FN is only valid on UNIX platforms and is used to specify an executable object (callable object) that will be invoked before the child process runs. CLOSE_SFS: Under the Windows platform, if the Close_fds is set to true, the newly created subprocess 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 errors (stdin, stdout, stderr) of the subprocess. The shell is set to true and the program is executed through the shell. CWD is used to set the current directory of child processes.If you run a subprocess that needs to be run under the specified directory, you can set this up. The env is a dictionary type that specifies the environment variable for a child process. If env = None, the child process's environment variable inherits from the parent process. 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. Startupinfo and Creationflags are used only 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.If you need to run in the new CMD window, you need to set up Creationflags =subprocess under Windows. Create_new_console.



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 method of Popen

1.popen.poll (): Used to check whether the child process has ended. Sets and returns the ReturnCode property.

2.popen.wait (): Wait for child process to end. Sets and returns the ReturnCode property.

3.popen.communicate (Input=none): interacts with child processes. 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.

4.popen.send_signal (signal): Sends a signal to a child process.

5.popen.terminate (): Stops (stop) child process. Under Windows platform, this method calls the Windows API terminateprocess () to end the subprocess.

6.popen.kill (): Kills the child process.

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

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

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

10.popen.pid: Gets the process ID of the child process.

11.popen.returncode: Gets the return value of the process. Returns none if the process is not yet finished.

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

13.subprocess.check_call (*popenargs, **kwargs): As with the Subprocess.call (*popenargs, **kwargs) function, The calledprocesserror exception is triggered only if the ReturnCode returned by the child process is not 0. In the exception object, include the ReturnCode information for the process.

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.