📅  最后修改于: 2023-12-03 15:19:01.506000             🧑  作者: Mango
The subprocess.run
function in Python is a versatile way to execute shell commands or other programs from within a Python script. It allows you to easily interact with the command line, capture the output, and handle errors.
The basic syntax of subprocess.run
is as follows:
subprocess.run(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)
args
: This can be a string or a sequence of strings that represent the command(s) you want to run.stdin
: An optional input stream to be passed to the command.input
: An alternative to stdin
as a string to be passed as input to the command.stdout
: The output stream to capture the standard output of the command.stderr
: The output stream to capture the standard error of the command.capture_output
: If set to True
, both stdout
and stderr
will be captured.shell
: If set to True
, the command will be executed through the shell.cwd
: The current working directory for the command to be executed.timeout
: The maximum amount of time to wait for the command to complete.check
: If set to True
, an exception is raised if the command exits with a non-zero status.encoding
: The character encoding to use for the input/output streams.errors
: The error handling scheme to use for decoding input/output streams.text
: If set to True
, the input/output streams will be treated as text streams.env
: A mapping of environment variables to pass to the command.universal_newlines
: If set to True
, the input/output streams will be opened as text files.The subprocess.run
function returns a CompletedProcess
object that represents the executed command. This object contains information about the command's return code, output, and error.
import subprocess
result = subprocess.run('ls -l', shell=True, capture_output=True, text=True)
print(result.stdout)
import subprocess
result = subprocess.run(['echo', 'Hello, Python'], capture_output=True, text=True)
output = result.stdout.strip()
print(output)
import subprocess
try:
subprocess.run('invalidcommand', check=True)
except subprocess.CalledProcessError as e:
print(f'Error: {e}')
The subprocess.run
function in Python allows you to execute shell commands or other programs with ease. It provides various options for capturing output, handling errors, and tweaking the execution environment. This flexibility makes it a powerful tool for interacting with the command line from within your Python scripts.