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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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