How to a Run Bash Command in Python

If you need to run a bash command in your Python code, then you can do the following:

Option 1 – Using run() from subprocess Module

from subprocess import PIPE

comp_process = subprocess.run("ls",stdout=PIPE, stderr=PIPE)
print(comp_process.stdout)

Option 2 – Using Popen() from subprocess Module

from subprocess import PIPE

process = subprocess.Popen("ls",stdout=PIPE, stderr=PIPE)
output, error = process.communicate()
print(output)
process.kill