subprocess.run() vs subprocess.Popen()
subprocess.run() and subprocess.Popen() are both Python Subprocess Module APIs, and choosing between them is a common point of confusion. This page compares their syntax, parameters, return values, and typical use cases so you can pick the right one. subprocess.run(): Runs a command and waits for it to complete. Returns a CompletedProcess instance. Its syntax is subprocess.run(args, *, stdin=None, input=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, text=None), and it returns completedProcess object subprocess.Popen(): Executes a child program in a new process (lower-level than run()). Its syntax is subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, env=None, text=None), and it returns popen object Example of subprocess.run(): import subprocess
r = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(r.stdout) # Command output
print(r.returncode) # 0 = success. Example of subprocess.Popen(): p = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE)
output, _ = p.communicate()
print(output.decode()). Read the full references for subprocess.run() and subprocess.Popen() to see parameters, edge cases, and example code side by side.