QA
Intermediate LevelPython

How do you execute external shell commands securely and capture stdout/stderr using subprocess.run()?

❓ Interview Prompt: Explain `subprocess.run()`, capturing output (`capture_output=True`), handling non-zero exit codes (`check=True`), and preventing shell injection.

'subprocess.run()' is the standard way to execute external OS commands in Python:

Security & Best Practice:

•
Pass argument list ('['ls', '-lh']') instead of string with 'shell=True' to prevent Command Injection Vulnerabilities!
•
'check=True': Automatically raises 'CalledProcessError' if the subprocess exits with a non-zero status code.

Code Implementation Example

python
import subprocess

try:
    # Execute system git command safely passing argument list
    result = subprocess.run(
        ['git', 'version'],
        capture_output=True,
        text=True,
        check=True
    )
    print('Output:', result.stdout.strip())
except subprocess.CalledProcessError as err:
    print('Command failed:', err)
💡Executing external system commands safely using subprocess.run().
🎯 Interview Key Takeaway

Always pass arguments as a list to subprocess.run() and avoid shell=True to prevent command injection attacks.

#subprocess#subprocess.run#Security#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?