Create a sub-process using Python subprocess

Source: Internet
Author: User
Tags python subprocess

Python provides multiple modules for creating sub-processes. I prefer to use the subprocess module because the python manual contains the following:

This module intends to replace several other, 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. *, and commands .*. It can be seen that subprocess is a recommended module.

Module selection comparison

1. OS. System ()
Disadvantages:
A. OS. System () is a new shell to work, which has a high overhead on the system.
B. It is troublesome to obtain output information and cannot interact with external commands or tools.
C. unable to control, (if an external command is called, it will be suspended or the execution takes a long time), the main process cannot control the OS. system (), because OS. system (CMD) calls the process to block, until OS. system () quit by yourself

2. Commands
Advantages:
A. It is easy to get the output of External commands, and the output has exited.
Disadvantages:
Same as a, c in OS. System ()

3. OS. popen ()
Same as commands command

4. subprocess
Advantages:
A. Interaction with sub-processes is supported.
B. Support synchronous/asynchronous sub-process execution
C. subprocess communication is supported.
D. Customizable Io Pipelines
E. You can determine whether to enable new shell tasks.
.......

Subprocess. popen

The Subprocess module defines only one class: popen. You can use popen to create a process and perform complex interaction with the process. 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: it can be a string or a sequence type (such as list and tuples). It is used to specify the executable file and its parameters of a process. 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. It has never been used so far.
  • Executable: 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.
  • Stdin, stdout, and stderr indicate the standard input, output, and error handle of the program respectively. They can be pipe, file descriptor or file object, or set to none, indicating that they are inherited from the parent process.
  • Preexec_fn 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 will not inherit the input, output, and error pipelines 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 shell is set to true, the program will be executed through shell.
  • CWD is used to set the current directory of the sub-process.
  • An env is a dictionary type used to indicate the environment variables of a child process. If Env = none, the environment variables of the child process are inherited from the parent process.
  • Universal_newlines: 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.
  • Startupinfo and createionflags are valid only in windows. They are passed to the underlying CreateProcess () function 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

1. popen. Poll (): used to check whether the sub-process has ended. Set and return the returncode attribute.

2. popen. Wait (): Wait until the sub-process ends. Set and return the returncode attribute.

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

4. popen. send_signal (signal): sends signals to sub-processes.

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

6. popen. Kill (): kills sub-processes.

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

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

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

10. popen. PID: gets the ID of the sub-process.

11. popen. returncode: gets the return value of the process. If the process has not ended, none is returned.

12. 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. If the sub-process does not need to interact with each other, you can use this function to create a sub-process.

13. subprocess. check_call (* popenargs, ** kwargs): With subprocess. the call (* popenargs, ** kwargs) function is the same, but if the returncode returned by the sub-process is not 0, the calledprocesserror exception is triggered. The exception object contains the returncode information of 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.