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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap