Python: How to execute terminal commands

Sep 24, 2020 | - views

import subprocess

# Execute command cmd in terminal
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout, stderr = proc.communicate()
if proc.returncode != 0:
    raise RuntimeError('Command '%s' returned non-zero exit status %d: %s' % (cmd, proc.returncode, stdout))