()
() is a wrapper around the system() system function in C. It allows you to execute a command and return an exit code. The output of the command is printed directly to the screen and is not directly accessible.
Example:
# import os ("ls -l | grep test") # Allow pipeliners # Test execution $ ll <======== List the contents of the current directory drwxr-xr-x 2 foo foo 4096 Feb 13 09:09 __pycache__ -rw-r--r-- 1 foo foo 359 Feb 19 09:21 $ python -rw-r--r-- 1 foo foo 359 Feb 19 09:21 <======== Only names containing test The documents are listed
()
This is the recommended method for executing commands starting with Python 3.5, and has the following prototype:
( args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None )
Among them:
args: can be a string (when shell=True) or a list (when shell=False)
- stdin, stdout, stderr: Used to specify standard IO file handles, can be:
: serve as stdout, stderr When the value of the parameter,can be retrieved from the return value object in the stdout cap (a poem) stderr Read the output in the attribute : serve as stderr When the value of the parameter,Equivalent to redirecting standard errors to standard inputs) : serve as stdout, stderr When the value of the parameter,This is equivalent to redirecting the output to the /dev/null File objects or descriptors that have been opened by the user(integer number)
capture_output: when set to True, it is equivalent to stdout and stderr parameters are set to True, you can access the standard output and standard error content through the return value object.
shell: when set to True, the args parameter is treated as a command string (piping and redirection are supported); when it is False, args needs to be a list (and piping and redirection are not supported)
cwd: Specifies the directory where the command is executed, defaults to the current directory.
timeout: Specify the command execution timeout (in terms of Mythical), if the execution timeout is exceeded, the command will be killed and a TimeoutExpired exception will be thrown.
check: when set to True, the execution exit code is automatically detected, if it is not 0, then a CalledProcessError exception is thrown.
text: when set to True, stdin, stdout, stderr will be opened in "text" mode (stdout, stderr in the return value object store text content), otherwise stdout, stderr in the return value object store byte sequences.
env: Used to set the environment variables inherited by the program execution, etc., the default is the same as the current process.
This method returns a CompletedProcess object containing the following properties:
- returncode: the exit code of the executed command
- stdout: the standard output of the capture (when the stdout parameter is PIPE). The format defaults to a sequence of bytes, unless the text parameter is True (in which case it is in text format).
- stderr: The content of the standard error captured (when the stderr parameter is PIPE). The format defaults to a sequence of bytes, unless the text parameter is True (in which case it is in text format).
- args: same as args.
Example:
import subprocess (["ls", "-l"]) # By default, the args parameter must be a list ("ls -l", shell=True) # When shell is True, args is a string ret = ("ls -l", shell=True, capture_output=True, text=True) # Capture output in text mode print("Return code:", ) # Return code: 0 print("STDOUT:", ) # STDOUT: ... Current directory contents... print("STDERR:", ) # STDERR: <null> ret = ("abcdefg", shell=True, text=True, # Note: shell=True is required to catch /bin/sh output errors. # When shell=False, it's meant to capture the output of the "abcdefg" command itself, but it doesn't exist, and python throws an error. stdout=, stderr= # Standard errors redirected to standard output ) print("STDOUT:", ) # STDOUT: /bin/sh: abcdefg: command not found
Another example for testing the difference between shell arguments is as follows:
import sys, re, subprocess if len() == 1: # parent process cmd = ["python", [0], "--run-child"] ret = (cmd, stdout=, stderr=, text=True) print(ret) # CompletedProcess(args=['python', '', '--run-child'], returncode=0, stdout='stdout output\n', stderr='stderr output') assert ("stdout output", ) assert ("stderr output", ) # If the command doesn't exist in cmd, it's not captured here, and () itself will report an error ret = (" ".join(cmd), shell=True, stdout=, stderr=, text=True) print(ret) # CompletedProcess(args='python --run-child', returncode=0, stdout='stdout output\n', stderr='stderr output') assert ("stdout output", ) assert ("stderr output", ) # If the command in the cmd does not exist, it is also captured here, which may read xxx command not found print("Passed!") else: # child process print("stdout output") ("stderr output")
()
Python 3.5 and earlier (including releases) did not have the () method; you can use () to execute commands, which has the following prototype:
(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None)
Note: The return value of this method is the exit code of the command, not an object, so it is not possible to capture the contents of the command output like () (don't set stdout=PIPE or stderr=PIPE, or the command may get stuck).
The other parameters of this method are similar to ().
.check_output()
Prior to Python 3.5, to capture the contents of the command output, you can use the subprocess.check_output() method, which has the following prototype:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None)
Note: There is no stdout in the argument, because the return value of this function is the standard output by default, or you can set stderr= to redirect standard errors to standard output, but there seems to be no way to capture the standard error content alone!
Example:
import sys, re, subprocess if len() == 1: # parent process cmd = ["python", [0], "--run-child"] ret = subprocess.check_output(cmd, stderr=) print("[" + ret + "]") # The output contains standard output and standard errors, the order of output may differ between windows and linux. assert ("stdout output", ret) assert ("stderr output", ret) print("Passed!") else: # child process print("stdout output") ("stderr output")
to this article on the use of Python (), (), call (), check_output () of the article on this, more related to Python (), (), call (), check_output () content, please search for my previous articles or continue to browse the following related articles I hope that you will support me in the future!