Python subprocess module (original) (raw)

The subprocess module is used to run external programs or system commands from Python. It allows to execute commands, capture their output and interact with other processes. One can also send input, handle errors and check execution status.

**Example: In this example, a system command is executed to check the Python version and print its output.

Python `

import subprocess res = subprocess.run(["python", "--version"], capture_output=True, text=True) print(res.stdout)

`

**Explanation:

subprocess.run()

subprocess.run() executes a command and waits until it finishes. It returns an object that contains output, errors and return status of the command.

**Example: Here, a command is executed and both output and return code are printed.

Python `

import subprocess res = subprocess.run(["python", "--version"], capture_output=True, text=True) print("Output:", res.stdout) print("Return Code:", res.returncode)

`

Output

Output: Python 3.13.0

Return Code: 0

**Explanation:

subprocess.Popen

Popen starts a new process and allows interaction with it while it is running. It gives control over input, output and error streams.

**Example: In this example, a process is started and its output is captured.

Python `

import subprocess

process = subprocess.Popen( ["python", "--version"], stdout=subprocess.PIPE, text=True )

output, _ = process.communicate() print(output)

`

**Explanation:

subprocess.check_output

check_output() executes a command and returns only its output. If the command fails, it raises an exception.

**Example: Here, a command is executed and its output is directly returned.

Python `

import subprocess try: output = subprocess.check_output(["python", "--version"], text=True) print(output) except subprocess.CalledProcessError: print("Command failed")

`

**Explanation:

subprocess.call

subprocess.call() runs a command and returns its exit status. It does not store output in variables.

**Example: In this example, a command is executed and its success status is checked.

Python `

import subprocess code = subprocess.call(["python", "--version"])

if code == 0: print("Success") else: print("Failed")

`

Output

Python 3.13.0 Success

**Explanation:

subprocess Pipes

Pipes are used to send input to a process and receive output from it. This helps in communication between processes.

**Example: Here, input is sent to a Python process and the result is captured.

Python `

import subprocess process = subprocess.Popen( ["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True )

output, _ = process.communicate("print(5 + 5)") print(output)

`