VOOZH about

URL: https://www.geeksforgeeks.org/python/python-subprocess-module/

⇱ Python subprocess module - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python subprocess module

Last Updated : 4 Apr, 2026

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.


Output
Python 3.13.0

Explanation:

  • subprocess.run() executes the command
  • capture_output=True stores output instead of printing directly
  • text=True converts output to string
  • result.stdout contains the output

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.


Output
Output: Python 3.13.0

Return Code: 0

Explanation:

  • subprocess.run() runs the command and waits
  • res.returncode gives execution status (0 means success)
  • res.stdout stores command output

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.


Output
Python 3.13.0

Explanation:

  • subprocess.Popen() starts the process
  • stdout=subprocess.PIPE captures output
  • process.communicate() reads output and waits for completion

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.


Output
Python 3.13.0

Explanation:

  • subprocess.check_output() runs the command
  • Returns output directly and raises error if execution fails

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.


Output
Python 3.13.0
Success

Explanation:

  • subprocess.call() executes the command
  • Returns 0 if successful
  • Output is printed directly to terminal

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.


Output
10

Explanation:

  • stdin=subprocess.PIPE allows sending input
  • stdout=subprocess.PIPE captures output
  • process.communicate() sends input and reads result
Comment
Article Tags: