Python POpen Subprocess Examples

We can make use of the Python subprocess module to spawn new processes and connect to their input/output/error pipes, and obtain their return codes.


Note: subprocess module does not work or is not available on WebAssembly platforms wasm32-emscripten and wasm32-wasi.


Subprocess Popen Class

    The subprocess.Popen() constructor is responsible for the creation and management of the sub-processes in this Subprocess module.


Example Subprocess Module:

import subprocess

ls_command = ["ls", "-ltrh"]
process = subprocess.Popen(ls_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
stdout, stderr = process.communicate()

print("Process Standard Output:")
print(stdout)
print("Process Standard Error:", stderr)
print("Process Return Code:", process.returncode)
Output:
Process Standard Output:
total 4.0K
drwxr-xr-x 1 root root 4.0K Aug  9 13:37 sample_data

Process Standard Error: 
Process Return Code: 0
Python POpen Subprocess Example

References:

- https://docs.python.org/3/library/subprocess.html

- https://docs.python.org/3/library/subprocess.html#subprocess.Popen

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!