How to run bash commands inside of a Python script [duplicate]

Use subprocess, e.g.:

import subprocess
# ...

subprocess.call(["echo", i])

There is another function like subprocess.call: subprocess.check_call. It is exactly like call, just that it throws an exception if the command executed returned with a non-zero exit code. This is often feasible behaviour in scripts and utilities.

subprocess.check_output behaves the same as check_call, but returns the standard output of the program.


If you do not need shell features (such as variable expansion, wildcards, …), never use shell=True (shell=False is the default). If you use shell=True then shell escaping is your job with these functions and they’re a security hole if passed unvalidated user input.

The same is true of os.system() — it is a frequent source of security issues. Don’t use it.

Leave a Comment