Back
+15 XP
Concept

Spawning External Commands with subprocess.run

`subprocess.run(args, capture_output=True, text=True)` is the modern standard for executing system CLI commands safely without shell injection vulnerabilities 💻.

python
import subprocess

# Pass arguments as a list, NOT a raw string:
result = subprocess.run(
    ["echo", "Hello from system process!"],
    capture_output=True,
    text=True
)

print(f"Stdout: {result.stdout.strip()} 💻")
print(f"Exit code: {result.returncode} ✅")

# 101. Spawning External Commands with subprocess.run `subprocess.run(args, capture_output=True, text=True)` is the modern standard for executing system CLI commands safely without shell injection vulnerabilities 💻. ```python import subprocess # Pass arguments as a list, NOT a raw string: result = subprocess.run( ["echo", "Hello from system process!"], capture_output=True, text=True ) print(f"Stdout: {result.stdout.strip()} 💻") print(f"Exit code: {result.returncode} ✅") ``` Never use `shell=True` when passing untrusted user input; passing argument lists directly bypasses bash subshell interpolation and prevents command injection! 💻 --- ### Question Why should arguments be passed as a list (e.g. `['ls', '-l']`) rather than a single string with `shell=True`? 🧠 - [ ] a. Prevents shell injection security vulnerabilities and avoids subshell overhead 💻 - [ ] b. Because Python cannot parse spaces in strings - [ ] c. Lists execute faster in the CPU arithmetic logic unit - [ ] d. Operating systems reject string commands --- ### Challenge Import `subprocess`. Run `['echo', 'PY_OK']` with `capture_output=True, text=True`. Print `result.stdout.strip()`. 🎯 <details> <summary>Solution</summary> ```python import subprocess result = subprocess.run(["echo", "PY_OK"], capture_output=True, text=True) print(result.stdout.strip()) ``` </details>

Checkpoint

Why should arguments be passed as a list (e.g. `['ls', '-l']`) rather than a single string with `shell=True`? 🧠

Practice

Import `subprocess`. Run `['echo', 'PY_OK']` with `capture_output=True, text=True`. Print `result.stdout.strip()`. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks