This article will demonstrate practical approaches to run a bash script/command from within Python code. However, the article will cover the following outline:
- Prerequisite: Install Python on Linux
- Run Bash Script Using Subprocess Module
- Run Bash Script Using the OS module
- Bonus Tip: Run Bash Commands in Python
- Conclusion
Prerequisite: Install Python on Linux
Python(a high-level scripting language) is a widely used and general-purpose coding language all over the world. The Python programmers are usually required to run the bash script within the program for task automation. Usually, python3 is preinstalled in Linux distribution. In case, if python is not installed on the system, install it by following the below instructions.
Step 1: Update and Upgrade the APT repository
First, launch the Linux terminal using the “CTRL+ALT+T” key or from the activity menu. After that, update the Linux APT repository:
Next, upgrade the repository using the “apt upgrade” command:
Step 2: Install Python
Now, install Python on the machine by executing “apt install python3” command with “sudo” privileges:
Step 3: Verification
To check if Python is installed on the system or not, use the “apt show” command:
The below output shows that python3 version “3.11.2” is installed on the system:
How to Run Bash Script Using a Subprocess Module?
The subprocess module is the latest Python module that is utilized to spawn processes, process I/O, and err stream, and get return results. It is the replacement of Python older modules such as Os. To run the bash script from the Python program, follow the given instructions.
Example 1: Run Bash Script Using “subprocess.run”
The “subprocess.run” process is utilized to execute the subprocess, so, use the run() method of the “subprocess” module to run the existing bash script. To run the bash script using the subprocess method “run()”, follow the given instructions.
Step 1: Create Bash Script
Create a new file name “bash_script.sh” using nano text editor. For this purpose, execute the given command:
Start the file with “#!/bin/bash” to specify the bash commands. After that, add the required command into the bash script. For instance, we have added the “echo” command:
echo "Hello! Welcome to Linuxhint Tutorial"
To save the bash script, use the “CTRL+S” key, and to exit the editor, press “CTRL+X”.
Step 2: Create a Python Program
Next, create the Python program file “filename.py” in a nano text editor:
Import the “subprocess” module, use the “subprocess.run” method, pass the path to bash script as a parameter, and set the “shell” parameter value as true:
print (subprocess.run([r"./bash_script.sh", "arguments"], shell=True))
Next, save the file and exit the nano editor.
Step 3: Make Bash Script Executable
To execute the bash script within the Python program, the user must set its permission as executable. For this purpose, execute the below command:
Step 4: Run the Python Program
Run the Python file to execute the Python program. For this purpose, use the “python3 <filename.py>” command:
The output shows that we have effectively run the bash script from the Python program:
Example 2: Run Bash Script Using “subprocess.call”
The subprocess module “call()” method is used to execute the commands and wait until the processing of the command is completed. In the example demonstrated below, the same bash file is used that was used in the above example. To run the bash script using the “subprocess.call” method, follow the given instructions.
Step 1: Create a Python Program
Create and open the Python program file in a nano text editor as done in the above example. After that, paste the following code into the file:
print("Running Bash Script”)
subprocess.call(r"./bash_script.sh", shell=True)
print("Operation Successfull")
In the above snippet, the “subprocess.call” method passes two parameters, one is “path to bash script”, and the second is “shell”:
Step 2: Run Python Program
After that, run the program using the given command:
The below result indicates that we have successfully executed the bash script using the “subprocess.call” method:
How to Run Bash Script Using an OS module?
The “OS” module of Python is used to interact with the operating system which is mostly used to create the folder, access the folder content, or make modifications. To access and execute the bash script from Python, the os python module can be used. To do so, follow the listed steps.
Step 1: Create a Python Program
In this example, the same bash script is used that was used in the above section. Next, paste the following code into the Python program file:
os.system('sh bash_script.sh')
Step 2: Run Python Program
Run the Python program to execute the bash script using the “os” module:
Here, you can see we have successfully run the bash script using the Python “os” module:
Users can also run the bash commands within Python code. To get an insight into how bash commands are executing, follow the next section.
Bonus Tip: Run Bash Commands in Python
To run the bash command within the Python program directly, go through the following examples.
Example 1: Run Bash Command in Python Using “subprocess.run”
Run the bash command to list down the directory and files along with permissions details using “ls” and “-l” commands. These commands can be executed using the “subprocess.run” method of the Python “subprocess” module:
subprocess.run(["ls", "-l"])
Now, run the Python program file:
You can see we have effectively listed down the current directory files by executing the bash command from the Python program:
Example 2: Run Bash Command in Python Using “subprocess.Popen”
The process creation and management of the subprocess module is done through the “Popen” subprocess class. To execute the bash command from the python program run, paste the below snippet into the python program file:
popen_process = subprocess.Popen (["echo", "Welcome to Linuxhint Tutorial"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
output= popen_process.communicate( )
print(output)
In the above snippet, the “communicate()” function will interact with the operating system application and open the file:
Execute the program file to run the bash command from Python:
The output indicates that the Python program executed the bash command successfully:
Example 3: Run Bash Command in Python Using “os.system”
The “os.system” method of the python “os” module can also execute the bash command directory. For this purpose, go through the below snippet that will list down current directory files and print some string on the console using bash commands:
os.system("ls")
os.system("echo Successfully executed bash commands")
Now, run the Python program using “python3 <filename.py>”:
We have successfully executed the bash command directory from Python:
We have covered how to run bash scripts and commands from Python.
Conclusion
To run a bash script from Python, the “os” and “subprocess” modules are used. When executing a bash script “os” module interacts with the operating system and processes output accordingly. However, the “subprocess” module takes input, and returns output along with processing other functions and methods like run(), call(), and Popen(). This article is all about executing bash scripts from Python.