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 =['whoami'], capture_output=True, text=True)



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 =['python', '--version'], capture_output=True, text=True)


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:

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