subprocess.Popen() vs Popen.communicate()
subprocess.Popen() and Popen.communicate() 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.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 Popen.communicate(): Sends data to stdin and reads from stdout/stderr until EOF. Its syntax is Popen.communicate(input=None, timeout=None), and it returns (stdout, stderr) tuple Example of subprocess.Popen(): p = subprocess.Popen(["ping", "google.com"], stdout=subprocess.PIPE)
output, _ = p.communicate()
print(output.decode()). Example of Popen.communicate(): p = subprocess.Popen(["sort"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, _ = p.communicate(b"3\n1\n2\n")
print(out) # b"1\n2\n3\n". Read the full references for subprocess.Popen() and Popen.communicate() to see parameters, edge cases, and example code side by side. Other Subprocess Module APIs worth comparing: subprocess.run(), subprocess.call(), subprocess.check_output(), subprocess.check_call(), subprocess.PIPE, subprocess.DEVNULL.