Block 132: subprocess: Running System Commands
Execute shell commands and capture output from Python.
Concepts
- subprocess.run() with capture_output=True
- Checking returncode for success/failure
- subprocess.Popen() for long-running processes
- Security: never pass user input to shell=True
Code Examples
See exercise below.
Exercise
Run 'ls' or 'dir' from Python and print the output. Run 'ping' or 'nslookup' and capture stdout to a file.
Homework
What is the security risk of subprocess.run('command ' + user_input, shell=True)? How do you avoid it? Tuesday