# import subprocess **[import subprocess](https://docs.python.org/3/library/subprocess.html)** is a Python import that runs external programs and captures their output. Use `subprocess.run()` to execute commands from Python. ## Example ```python # Python # description: run external commands, capture output import subprocess # Run command and capture output result = subprocess.run(["ls", "-la"], capture_output=True, text=True) print(result.stdout) print(f"Exit code: {result.returncode}") # Run with input/output pipes result = subprocess.run(["grep", "error"], input="line 1\nerror line\nline 3\n", capture_output=True, text=True) print(result.stdout) # Check if command succeeded result = subprocess.run(["python", "--version"], capture_output=True, text=True) if result.returncode == 0: print(f"Success: {result.stdout.strip()}") # Run shell command (less secure, use with caution) result = subprocess.run("ps aux | grep python", shell=True, capture_output=True, text=True) print(result.stdout) ``` ## Common functions - `subprocess.run(args)`: run command and wait for completion - `capture_output=True`: capture stdout and stderr - `text=True`: return strings instead of bytes - `input=...`: pass input to subprocess - `check=True`: raise exception if command fails - `cwd=...`: working directory for command - `shell=True`: run through shell (less secure) - `result.returncode`: exit code - `result.stdout`, `result.stderr`: captured output