Python - execute shell commands in subprocess


Python tip:

Use the subprocess module to spawn new processes.

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

Use Popen.communicate to capture result and errors.

An example👇

import subprocess

proc = subprocess.Popen(
    ["ls", "-la", "/home/johndoe/Images"],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
)
output, err = proc.communicate()

if err:
    raise Exception(err.decode())

print(output.decode())
"""
drwxrwxr-x   2 johndoe  johndoe    4096 Sep 28 08:17 .
drwxr-xr-x  13 johndoe  johndoe    4096 Sep 28 08:12 ..
-rw-rw-r--   1 johndoe  johndoe  115887 Sep 19 09:15 1_initial_user.png
-rw-rw-r--   1 johndoe  johndoe  115055 Sep 19 09:15 2_change_ban.png
-rw-rw-r--   1 johndoe  johndoe  114587 Sep 19 09:15 4_change_database.png
-rw-rw-r--   1 johndoe  johndoe  188718 Sep 19 09:15 5_srp.png
-rw-rw-r--   1 johndoe  johndoe  188718 Sep 19 09:15 change_charge.png
"""