YouTip LogoYouTip

Python Subprocess

Python3.x Python subprocess Module

\n\n

subprocess is a module in the Python standard library used for creating and managing child processes.

\n\n

subprocess allows you to execute external commands within a Python program and interact with these commands.

\n\n

Through the subprocess module, you can execute system commands, call other programs, and obtain their output or error information.

\n\n

Why use the subprocess module?

\n\n

In Python, sometimes we need to execute some system commands or call other programs to complete specific tasks. For example, you might need to run a shell command, start an external application, or interact with a command-line tool. The subprocess module provides a secure and flexible way to handle these needs.

\n\n

Compared to older methods like os.system() or os.popen(), the subprocess module offers more powerful features and better control capabilities. It allows you to manage the input, output, and error streams of child processes more finely and can handle more complex scenarios.

\n\n
\n\n

1. Executing External Commands

\n\n

subprocess.run() is one of the most commonly used functions in the subprocess module. It can execute an external command and wait for the command to complete. Here is a simple example:

\n\n

Example

\n\n
import subprocess\n\n# Execute a simple shell command\nresult = subprocess.run(['ls', '-l'], capture_output=True, text=True)\n\n# Print the command's output\nprint(result.stdout)\n
\n\n

In this example, subprocess.run() executes the ls -l command and captures the output into result.stdout.

\n\n

2. Handling Input and Output

\n\n

The subprocess module allows you to control the input, output, and error streams of the child process. You can pass data to the standard input of the child process or read data from the standard output and standard error of the child process. Here is an example:

\n\n

Example

\n\n
import subprocess\n\n# Execute a command and pass input to the child process\nresult = subprocess.run(['grep', 'python'], input='hellon pythonn world', capture_output=True, text=True)\n\n# Print the command's output\nprint(result.stdout)\n
\n\n

In this example, subprocess.run() executes the grep python command and passes the string 'hellonpythonnworld' as input to the child process.

\n\n

3. Handling Errors

\n\n

The subprocess module also allows you to handle errors from the child process. If the child process returns a non-zero exit status code, subprocess.run() will throw a CalledProcessError exception. You can get the exit status code of the child process by checking result.returncode.

\n\n

Example

\n\n
import subprocess\n\ntry:\n    result = subprocess.run(['ls', 'nonexistent_file'], capture_output=True, text=True, check=True)\nexcept subprocess.CalledProcessError as e:\n    print(f"Command failed with return code {e.returncode}")\n    print(f"Error output: {e.stderr}")\n
\n\n

In this example, subprocess.run() executes the ls nonexistent_file command. Since the file does not exist, the command fails and throws a CalledProcessError exception.

\n\n
\n\n

Advanced Usage of the subprocess Module

\n\n

1. Using the Popen Class

\n\n

The subprocess.Popen class provides a lower-level interface, allowing you to control the child process more flexibly. You can use Popen to start a child process and run it in the background, or interact with it.

\n\n

Example

\n\n
import subprocess\n\n# Start a child process\nprocess = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE, text=True)\n\n# Read the output of the child process\nwhile True:\n    output = process.stdout.readline()\n    if output == '' and process.poll() is not None:\n        break\n    if output:\n        print(output.strip())\n\n# Get the exit status code of the child process\nreturn_code = process.poll()\nprint(f"Process finished with return code {return_code}")\n
\n\n

In this example, subprocess.Popen starts a ping google.com command and runs it in the background. The program reads the output of the child process through a loop and obtains its exit status code after the child process ends.

\n\n

2. Using Pipes

\n\n

The subprocess module allows you to connect multiple commands together using pipes. You can use the output of one command as the input for another command.

\n\n

Example

\n\n
import subprocess\n\n# Connect two commands using a pipe\np1 = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)\np2 = subprocess.Popen(['grep', 'py'], stdin=p1.stdout, stdout=subprocess.PIPE, text=True)\n\n# Get the final output\noutput = p2.communicate()\nprint(output)\n
\n\n

In this example, the output of the ls -l command is passed to the grep py command, and the final output includes files or directories containing py.

\n\n
\n\n

Common Methods, Classes, and Parameters of the subprocess Module

\n\n

The following describes the common methods, classes, and parameters of the Python subprocess module, including functional descriptions and examples:

\n\n

subprocess Module Core Methods

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
MethodDescriptionExample
subprocess.run()Execute command and wait for completion (recommended)subprocess.run(["ls", "-l"], capture_output=True, text=True)
subprocess.Popen()Create child process (low-level control)proc = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE)
subprocess.call()Execute command and return exit code (legacy)exit_code = subprocess.call(["python", "--version"])
subprocess.check_call()Execute command, throw exception on failuresubprocess.check_call(["git", "commit"])
Minimal subprocess.check_output()Execute command and return output (legacy)output = subprocess.check_output(, text=True)
\n\n

subprocess.CompletedProcess Object Attributes (Return object of run() method)

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
AttributeDescription
argsExecuted command argument list
returncodeProcess exit status code (0 indicates success)
stdoutStandard output content (if capture_output is set)
stderrStandard error content (if capture_output is set)
\n\n

subprocess.Popen Class Common Methods/Attributes

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
Method/AttributeDescriptionExample
poll()Check if process has terminated (returns None if running)if proc.poll() is None: print("Running")
wait()Block and wait for process to endproc.wait()
communicate()Interactive input/outputstdout, stderr = proc.communicate(input="data")
terminate()Send termination signal (SIGTERM)proc.terminate()
kill()Force terminate process (SIGKILL)proc.kill()
stdinProcess standard input streamproc.stdin.write("input")
stdoutProcess standard output streamprint(proc.stdout.read())
stderrProcess standard error streamerrors = proc.stderr.read()
\n\n

Common Parameter Descriptions (Applicable to run() and Popen())

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
ParameterDescriptionExample Value
argsCommand (list or string)["ls", "-l"] or "ls -l"
stdMinimal inStandard input configurationsubprocess.PIPE (pipe), None (inherit)
stdoutStandard output configurationsubprocess.PIPE, open('log.txt', 'w')
stderrStandard error configurationsubprocess.STDOUT (merge to stdout)
shellWhether to execute via ShellTrue (supports string commands)
cwdWorking directory path"/tmp"
envCustom environment variables{"PATH": "/usr/bin"}
timeoutTimeout duration (seconds)30
textWhether input/output is string (not bytes)True
\n\n

Examples

\n\n

Execute command and capture output:

\n\n

Example

\n\n
result = subprocess.run(["echo", "Hello"], capture_output=True, text=True)\nprint(result.stdout) # Output: "Hellon"\n
\n\n

Execute complex command via Shell:

\n\n
subprocess.run("grep 'error' log.txt | wc -l", shell=True, check=True)\n
\n\n

Get output stream in real-time:

\n\n

Example

\n\n
proc = subprocess.Popen(["tail", "-f", "log.txt"], stdout=subprocess.PIPE)\nwhile True:\n    line = proc.stdout.readline()\n    if not line: break\n    print(line.decode().strip())\n
\n\n

Timeout control:

\n\n

Example

\n\n
try:\n    subprocess.run(["sleep", "10"], timeout=5)\nexcept subprocess.TimeoutExpired:\n    print("Command timed out!")\n
← Python StringioPython Sys β†’