Python sub-process module subprocess detailed and application examples of the second

Source: Internet
Author: User
Tags posix stdin dmesg

1.2. Popen Objects

An instance of the Popen class has the following methods:

1. Popen.poll ()

Checks whether the child process has ended, sets and returns the return code value.

2. Popen.wait ()

Waits for the child process to end, sets and returns the return code value.
WARNING: When using Stdout=pipe or stderr=pipe and the child process generates enough output information to the pipe so that the pipeline is blocked, it will cause a deadlock.
Use communicate () to avoid this situation.

3. Popen.communicate (Input=none)

Interact with child processes: Send data to stdin, read data from stdout and stderr until End-of-file is encountered. Wait for the child process to end.
The optional input parameter is a string that is passed to the child process, or None.
Communicate () returns a tuple (Stdoutdata, stderrdata).
Note: If you want to send data to the stdin of a child process, you need to set up stdin=pipe and create the Popen object.
Similarly, you need to set stdout=pipe or Stderr=pipe to get a non-null value in the returned result tuple.
In fact, the data read is buffered in memory, so do not use this method if the data is too large or infinite.

4. Popen.send_signal (signal)

Sends a signal signal to the child process.
Note: In Windows, Sigterm is an alias for terminate ().

5. Popen.terminate ()

Stop the subroutine, in the POSIX operating system, this method sends the Sigterm to the subroutine.

6. Popen.kill ()

Kill the child process, in the POSIX operating system, this upper function sends Sigkill to the child process.

The following properties are equally valid:
WARNING: Using Communicate () instead of. Stdin.write,. Stdout.read, or stderr.read, you can avoid deadlocks caused by pipeline blocking.
1. Popen.stdin
If the parameter value is PIPE, then this property value is a file object that is used to provide input to the child process.
Otherwise, it has a value of None.
2. Popen.stdout
If the parameter value is PIPE, then this property value is a file object that provides the output of the child process.
Otherwise, the value is None
3. Popen.stderr
If the stderr argument was PIPE, this attribute is a file object, which provides error output from the child process.
Otherwise, it is None.
4. Popen.pid
Process ID of the child process
Note that if you set the shell argument to True, this is the process ID of the spawned shell.
5. Popen.returncode
The return code of the child process, set by poll () and Wait () (and indirectly by communicate ().
A non-0 value indicates that the child process has not been ended.
A negative-n indicates that the child process is terminated by signal N.

1.3. Windows Popen using

The Startupinfo class and following constants is only available on Windows.
1. Class subprocess. Startupinfo
Partial support of the Windows STARTUPINFO structure are used for Popen creation.
2. DwFlags
A bit field that determines whether certain Startupinfo attributes is used when the process creates a window.
Si = subprocess. Startupinfo ()
Si.dwflags = subprocess. Startf_usestdhandles | Subprocess. Startf_useshowwindow
3. hStdInput
If dwFlags Specifies Startf_usestdhandles, this attribute are the standard input handle for the process. If
Startf_usestdhandles is isn't specified, the default for standard input is the keyboard buffer.
4. Hstdoutput
If dwFlags Specifies Startf_usestdhandles, this attribute are the standard output handle for the process. Otherwise,
This attribute are ignored and the default for standard output is the console window ' s buffer.
5. Hstderror
If dwFlags Specifies Startf_usestdhandles, this attribute are the standard error handle for the process. Otherwise,
This attribute are ignored and the default for standard error is the console window ' s buffer.
6. Wshowwindow
If dwFlags Specifies Startf_useshowwindow, this attribute can is any of the values that can is specified in the
nCmdShow parameter for the ShowWindow function, except for Sw_showdefault. Otherwise, this attribute is ignored.
7. Sw_hide is provided for this attribute. It was used when Popen was called with Shell=true.

1.3.1. Constants

The Subprocess module exposes the following constants.
Subprocess. Std_input_handle
The standard input device. Initially, this is the console input buffer, conin$.
Subprocess. Std_output_handle
The standard output device. Initially, this is the active console screen buffer, conout$.
Subprocess. Std_error_handle
The standard error device. Initially, this is the active console screen buffer, conout$.
Subprocess.sw_hide
Hides the window. Another window would be activated.
Subprocess. Startf_usestdhandles
Specifies that the startupinfo.hstdinput, Startupinfo.hstdoutput, and Startupinfo.hstderror attributes contain
Additional information.
Subprocess. Startf_useshowwindow
Specifies that the Startupinfo.wshowwindow attribute contains additional information.
Subprocess. Create_new_console
The new process has a new console and instead of inheriting its parent ' s console (the default).
This flag was always set when Popen was created with Shell=true.
Subprocess. Create_new_process_group
A Popen creationflags parameter to specify a new process group would be created.
This flag was necessary for using Os.kill () on the subprocess
This flag was ignored if Create_new_console is specified.

1.4. Replace the old function with the subprocess module

In the This section, "A becomes B" means that B can is used as a replacement for a.
Note all "A" functions in this section fail (more or less) silently if the executed program cannot is found;
The "B" replacements raise OSError instead.
In addition, the Replacements using Check_output () would fail with a calledprocesserror if the requested operation
Produces a Non-zero return code. The output is still available as the output attribute of the raised exception.
In the following examples, we assume the relevant functions has already been imported from the subprocess
Module.

1.4.1. replacing/bin/sh Shell Backquote

output= ' myCMD myarg '
# becomes
Output = Check_output (["myCMD", "Myarg"])

1.4.2. Replacing Shell Pipeline

output= ' DMESG | grep HDA '
# becomes
P1 = Popen (["DMESG"], Stdout=pipe)
P2 = Popen (["grep", "HDA"], Stdin=p1.stdout, Stdout=pipe)
P1.stdout.close () # allow P1 to receive a sigpipe if P2 exits.
Output = P2.communicate () [0]
The P1.stdout.close () call after starting the P2 are important in order for P1 to receive a sigpipe if P2 exits before P1.
Alternatively, for trusted input, the shell's own pipeline support could still be used directly:
output= ' DMESG | grep HDA '
# becomes
Output=check_output ("DMESG | grep hda ", shell=true)

1.4.3. Replacing Os.system ()

Status = Os.system ("mycmd" + "Myarg")
# becomes
Status = Subprocess.call ("mycmd" + "Myarg", Shell=true)
Notes:
Calling the program through the shell was usually not required.
A more realistic example would look like this:
Try
Retcode = Call ("myCMD" + "Myarg", Shell=true)
If Retcode < 0:
Print >>sys.stderr, "Child is terminated by signal",-retcode
Else
Print >>sys.stderr, "Child returned", Retcode
Except OSError as E:
Print >>sys.stderr, "Execution failed:", E

1.4.4. Replacing the Os.spawn family

p_nowait Example:
PID = OS.SPAWNLP (OS. P_nowait, "/bin/mycmd", "myCMD", "Myarg")
==>
PID = Popen (["/bin/mycmd", "Myarg"]). PID
p_wait Example:
Retcode = OS.SPAWNLP (OS. P_wait, "/bin/mycmd", "myCMD", "Myarg")
==>
Retcode = Call (["/bin/mycmd", "Myarg"])
Vector Example:
OS.SPAWNVP (OS. p_nowait, path, args)
==>
Popen ([path] + args[1:])
Environment Example:
Os.spawnlpe (OS. P_nowait, "/bin/mycmd", "myCMD", "Myarg", env)
==>
Popen (["/bin/mycmd", "Myarg"], env={"PATH": "/usr/bin"}

1.4.5. Replacing Os.popen (), Os.popen2 (), Os.popen3 ()

Pipe = Os.popen ("cmd", ' R ', bufsize)
==>
Pipe = Popen ("cmd", Shell=true, Bufsize=bufsize, stdout=pipe). StdOut
Pipe = Os.popen ("cmd", ' W ', bufsize)
==>
Pipe = Popen ("cmd", Shell=true, Bufsize=bufsize, stdin=pipe). stdin
(Child_stdin, child_stdout) = Os.popen2 ("cmd", Mode, bufsize)
==>
p = Popen ("cmd", Shell=true, Bufsize=bufsize,
Stdin=pipe, Stdout=pipe, Close_fds=true)
(Child_stdin, child_stdout) = (P.stdin, p.stdout)
(Child_stdin,
Child_stdout,
Child_stderr) = Os.popen3 ("cmd", Mode, bufsize)
==>
p = Popen ("cmd", Shell=true, Bufsize=bufsize,
Stdin=pipe, Stdout=pipe, Stderr=pipe, Close_fds=true)
(Child_stdin,
Child_stdout,
Child_stderr) = (P.stdin, p.stdout, P.stderr)
(Child_stdin, Child_stdout_and_stderr) = Os.popen4 ("cmd", Mode,
BufSize
==>
p = Popen ("cmd", Shell=true, Bufsize=bufsize,
Stdin=pipe, Stdout=pipe, Stderr=stdout, Close_fds=true)
(Child_stdin, Child_stdout_and_stderr) = (P.stdin, p.stdout)
On Unix, Os.popen2, Os.popen3 and Os.popen4 also accept a sequence as the command to execute, in which case arguments


'll is passed directly to the program without shell intervention. This usage can be replaced as follows:


(Child_stdin, child_stdout) = Os.popen2 (["/bin/ls", "-l"], mode,
BufSize
==>
p = Popen (["/bin/ls", "-l"], bufsize=bufsize, Stdin=pipe, Stdout=pipe)
(Child_stdin, child_stdout) = (P.stdin, p.stdout)
Return code handling translates as follows:


Pipe = Os.popen ("cmd", ' W ')
...
rc = Pipe.close ()
If RC is not None and RC >> 8:
Print "There were some errors"
==>
Process = Popen ("cmd", ' W ', Shell=true, Stdin=pipe)
...
Process.stdin.close ()
If process.wait ()! = 0:
Print "There were some errors"

1.4.6. Replacing functions from the Popen2 module

(Child_stdout, Child_stdin) = Popen2.popen2 ("somestring", bufsize, Mode)
==>
p = Popen ("somestring", Shell=true, Bufsize=bufsize,
Stdin=pipe, Stdout=pipe, Close_fds=true)
(Child_stdout, Child_stdin) = (p.stdout, P.stdin)
On Unix, Popen2 also accepts a sequence as the command to execute, in which case arguments'll be passed directly to
The program without shell intervention. This usage can be replaced as follows:

(Child_stdout, Child_stdin) = Popen2.popen2 (["myCMD", "Myarg"], Bufsize,mode)

==>
p = Popen (["myCMD", "Myarg"], Bufsize=bufsize,
Stdin=pipe, Stdout=pipe, Close_fds=true)
(Child_stdout, Child_stdin) = (p.stdout, P.stdin)
Popen2. Popen3 and Popen2. Popen4 basically work as subprocess. Popen, except that:
Popen raises an exception if the execution fails.
The Capturestderr argument is replaced with the stderr argument.
Stdin=pipe and Stdout=pipe must be specified.
Popen2 closes all file descriptors by default, and you have to specify Close_fds=true with Popen.

1.5. NOTES1.5.1. Converting an argument sequence-a string on Windows

On Windows, an args sequence are converted to a string that can be parsed using the following rules (which correspond
To the rules used by the MS C runtime):

Arguments was delimited by white space, which is either a space or a tab.
A string surrounded by double quotation marks are interpreted as a single argument, regardless of white space
Contained within. A quoted string can is embedded in an argument.
A double quotation mark preceded by a backslash is interpreted as a literal double quotation mark.
Backslashes is interpreted literally, unless they immediately precede a double quotation mark.
If backslashes immediately precede a double quotation mark, every pair of backslashes is interpreted as a literal
Backslash. If the number of backslashes is odd, the last backslash escapes the next double quotation mark as
Described in Rule 3.

Python sub-process module subprocess detailed and application examples of the second

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.