How to execute bash command from Python Code

If you want to execute a bash command from your Python code, you can do that by making use of the subprocess module. Let's take a look at an example.


Example 1:
import subprocess

ls_command_result = subprocess.run(['whoami'], capture_output=True, text=True)

print(ls_command_result.stdout)

root

If you want to add options with the command you can do that by passing it as an element of an array.

Example, if you want to know the version of Python.

Example 2:
import subprocess

python_version = subprocess.run(['python', '--version'], capture_output=True, text=True)

print(python_version.stdout)

Python 3.10.12


Example 3:
bash command python example

Comments & Discussion

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