CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium

A developer needs to write a Python script that executes an external shell command and captures its standard output and standard error streams separately. The script must also check the exit code of the command. Which `subprocess` module function is best suited for this task?

  1. A`subprocess.check_call()`
  2. B`subprocess.call()`
  3. C`subprocess.Popen()`
  4. D`subprocess.run()`
Show answer & explanation

Correct answer: D. `subprocess.run()`

`subprocess.run()` is the recommended high-level function for running external commands, introduced in Python 3.5. It returns a `CompletedProcess` object which conveniently contains `stdout`, `stderr`, and `returncode` attributes, making it ideal for capturing all required information.

Why the other options are wrong

  • A. `subprocess.check_call()` executes a command and raises a `CalledProcessError` if the exit code is non-zero, but it does not capture stdout/stderr by default.
  • B. `subprocess.call()` executes a command and returns its exit code, but does not easily capture stdout/stderr separately without additional pipes.
  • C. `subprocess.Popen()` provides fine-grained control for complex scenarios but is a lower-level API requiring manual handling of communication and wait. `subprocess.run()` is built on `Popen` for simpler cases.

Python `subprocess.run()`

The recommended high-level function in Python's `subprocess` module for executing external commands, introduced in Python 3.5.

  • Returns a `CompletedProcess` object.
  • Captures stdout and stderr by default when `capture_output=True` or `stdout=PIPE, stderr=PIPE`.
  • Handles waiting for the command to complete.
  • Collects the command's exit code in `returncode`.

Memory trick: Run the command, get all the results in one go.

More Automation, Orchestration and Scripting questions