Subprocess function: Create a child process, connect its input, output and error pipelines to get its return status (operating system-level commands can be executed in python code)
1. ()
Function: Execute the command represented by the args parameter, wait for the command to end, and return a CompletedProcess type object
1.1. Parameter introduction
(args,*,stdin=None,input=None,stdout=None,stderr=None,shell=False,timeout=None,check=False,encoding=None,errors=None)
- args: indicates the command to be executed, which must be a string or a string parameter list
- Stdin, stdout, stderr: Standard input, output and error of the child process, whose value can be, , an existing file descriptor, an open file object, or None
- timeout: Set the command timeout time. If the timeout, the child process will be killed and a TimeoutExpired exception will pop up.
- check: If this parameter is set to true and the process exit status code is not 0, a CalledProcessError exception pops up
- encoding: If this parameter is specified, stdin, stdout, stderr can receive string data and encode it in this encoding. Otherwise, it can only receive data of bytes type
- shell: If this parameter is True, the specified command will be executed through the operating system shell
1.1.1
The return value of run() indicates that a process has ended. CompletedProcess class has the following properties
- args: The parameter to start the process, usually a list or string
- returncode: The process end status return code, 0 indicates successful status
- stdout: Gets the stdout of the child process, usually a sequence of bytes type, None means there is no captured value.
- stderr: Get the error message of the child process, usually a sequence of bytes type, None means no captured value
- check_returncode(): Check the return code. If the return status code is not 0, a calledProcessError exception pops up
1.1.2
Special value for passing to stdout, stdin and stderr parameters
1.1.3
Pipe, can be passed to stdout, stdin, stderr parameters
1.1.4
Special value can be passed to the stderr parameter, indicating that the combined output of stdout and stderr can be used to use read(), readline(), readlines(), readlines() and other methods.
1.1.5 args and shell
- The args parameter can receive a string or pass a string split list.
- The shell parameter defaults to False. When set to True, it means to use the operating system shell to execute commands. When args is a string, shell=True must be specified; when args is a list, the shell remains the default False
1.2. Obtain execution results
The run() method returns a completedProcess type object, not the execution result. If you want to get the results or information of the command execution, when calling the run() method, you need to specify stdout=, and the result will be saved in the stdout attribute as the bytes type
1.2.1. Interactive input
The stdin parameter of the run() method can receive a file handle, as follows
import subprocess file=open("d:\\") ret=('python',stdin=file,stdout=,shell=True) print()
2. ()
Its usage and parameters are basically the same as run(), and can create and manage child processes, but its return value is a Popen object, not a CompletedProcess object.
2.1 Parameter introduction
class (args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0,restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None)
- args: shell command, can be a string or a sequence of characters
- bufsize: buffer size, default -1, pipe object used to create standard streams
- 0: No buffer is used
- 1: Indicates line buffering, only available when universal_newlines=True, i.e. text mode
- Positive number: indicates the buffer size
- Negative number: indicates the use of the system's default buffer size.
- stdin, stdout, stderr: respectively represent the standard input, output, and error handle of the program.
- preexec_fn: only valid on Unix platform, used to specify an executable object that will be called before the child process runs
- shell: If this parameter is True, the specified command will be executed through the operating system shell.
- cwd: Used to set the current directory of the child process.
- env: The environment variable used to specify the child process. If env = None, the environment variables of the child process will be inherited from the parent process.
2.1.1 Callable methods
- poll(): Check whether the process has terminated
- wait(): Wait for the child process to terminate
- communicate(input, timeout): interact with the child process, send and read data
- The data type of input must be a byte string. If universal_newlines=True, the data type of input parameter must be a string
- This method returns a tuple (stdout_data, stderr_data), byte string or string
- After the specified number of seconds of timeout, the process has not ended yet, and a TimeoutExpired exception will be thrown.
- send_signal(signal): Send a signal to the child process
- terminate(): Stop the child process, that is, send the SIGTERM signal to the child process
- kill(): Kill the child process and send SIGKILL
2.2 Example
The stdin, stdout, and stderr of the Popen object are three file handles, which can be read and written like a file. Data can be input through () and (). () can output data.
import subprocess s=('python3',stdout=,stdin=,shell=True) (b'import os\n') (b'print()') ()
3. Common functions for subprocess
function | Instructions for use |
---|---|
() | Execute the command represented by the args parameter, and return CompletedProcess after execution is completed. |
() | Execute the specified command, return the command execution status, similar to (cmd) |
subprocess.check_call() | Equivalent to (…, check=True) |
subprocess.check_output() | Execute the specified command. If the status code is 0, the command execution result will be returned, otherwise an exception will be thrown. |
() | Receive commands in string format, execute and return results, similar to (cmd).read() and (cmd) |
() | Execute the cmd command and return the tuple (command execution status, command execution result output) |
Attachment: python () executes the py script and waits for the script to be executed.
To use()
Execute a Python script and wait for the script to be executed, you can do it in the following ways:
import subprocess # File path to scriptscript_path = "/path/to/your/" # Use () to execute scripts(["python", script_path], capture_output=True, text=True) # The program will wait for the script to be executed here
In the above code:
-
"python"
It is the command to be executed. -
[script_path]
It is the parameter of the command, that is, the path to the Python script you want to execute. -
capture_output=True
Parameters represent the standard output and standard error flow of capture child processes. The result returned will be aCompletedProcess
Object, itsstdout
andstderr
Attributes contain standard output and standard error content respectively. -
text=True
The parameter indicates that the captured output is returned in text (valid in Python 3.7 and above).
()
It will block the current process until the command being called completes execution. The program will continue to execute subsequent code after execution is completed. If you don't want to capture the output, you can remove itcapture_output
Parameters.
Summarize
This is the article about the detailed explanation of the subprocess module of python learning. For more related content of subprocess module of python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!