import subprocess is a Python import that runs external programs and captures their output. Use subprocess.run() to execute commands from 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)
subprocess.run(args): run command and wait for completioncapture_output=True: capture stdout and stderrtext=True: return strings instead of bytesinput=...: pass input to subprocesscheck=True: raise exception if command failscwd=...: working directory for commandshell=True: run through shell (less secure)result.returncode: exit coderesult.stdout, result.stderr: captured output