Pcornel
Automation · Python Automation

subprocess

Cheat sheet · https://pcornel.dk/topic.php?topic=5264

Back to the Topic

Answer

subprocess runs external commands from Python, such as subprocess.run(['ping', '-c', '1', host], capture_output=True, check=True). Pass arguments as a list and avoid shell=True with untrusted input.

Remember

  • Use subprocess.run with a list of arguments.
  • check=True raises on non-zero exit.
  • Avoid shell=True with untrusted input.

First checks

  • python3 -c "import subprocess;print(subprocess.run(['echo','ok'],capture_output=True,text=True,check=True).stdout)" — safe call
  • No shell=True with user input — injection
  • timeout= set — hangs

Verify in this order

args list → subprocess → exit code/output

Where it usually breaks

Input/desired state → request accepted → job/task terminal status → target object read-back → effective runtime state → original workload → regression/rollback readiness.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=5264

Confirmation

Confirm action

Continue?