Site Tools


import-subprocess

import subprocess

import subprocess is a Python import that runs external programs and captures their output. Use subprocess.run() to execute commands from Python.

Example

# 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
import-subprocess.md · Last modified: by 127.0.0.1