CompTIA Linux+ (XK0-006)Automation, Orchestration and ScriptingMedium
A developer is creating a Python script that needs to interact with the operating system to list the contents of a directory. They want to execute the `ls -l` command and capture its standard output. Which `subprocess` module function is the most appropriate and recommended way to achieve this, while also handling potential errors?
- Asubprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0]
- Bos.system('ls -l')
- Csubprocess.run(['ls', '-l'], capture_output=True, text=True, check=True)
- Dsubprocess.call(['ls', '-l'])
Show answer & explanationAnswer & explanation
Correct answer: C. subprocess.run(['ls', '-l'], capture_output=True, text=True, check=True)
The `subprocess.run()` function is the recommended high-level API for running external commands. Using `capture_output=True` captures stdout/stderr, `text=True` decodes the output as text, and `check=True` raises an exception for non-zero exit codes, ensuring robust error handling.
Why the other options are wrong
- A. `subprocess.Popen()` is a lower-level API. While it can achieve the goal, `subprocess.run()` is preferred for simpler use cases as it encapsulates common patterns like capturing output and checking exit codes.
- B. `os.system()` is deprecated for complex use cases as it's less secure, doesn't capture output easily, and relies on the shell, making it harder to handle arguments safely.
- D. `subprocess.call()` executes the command and returns its exit code, but it doesn't capture output directly without additional `stdout` redirection.
Python `subprocess.run()`
The recommended high-level function in Python's `subprocess` module for running external commands and capturing their output.
- Replaces older functions like `call`, `check_call`, `check_output`.
- `capture_output=True` captures `stdout` and `stderr`.
- `text=True` (or `encoding`) decodes output to string.
- `check=True` raises `CalledProcessError` for non-zero exit codes.
Memory trick: Python runs external commands; choose wisely for control and safety.