In this tutorial, we will discuss how to run a Python script from a shell script. Running a Python script from a shell script is a useful technique when automating tasks or integrating Python with other scripting languages.
We will walk through the process step by step and explain how to create the necessary files and execute the Python script from the shell script.
Step 1: Create a Python script
First, create a Python script that you want to execute from the shell script. In this example, we will create a simple Python script named hello.py that will print “Hello, World!” to the console.
1 2 |
# hello.py print("Hello, World!") |
Save this script to a file named hello.py.
Step 2: Create a shell script
Now, create a shell script that will execute the Python script created in step 1. In this example, we will create a simple shell script named run_hello.sh that will execute the hello.py script.
1 2 |
!/bin/bash python3 hello.py |
Save this script to a file named run_hello.sh.
The first line of the shell script, #!/bin/bash, is known as a shebang. It instructs the system to use the Bash interpreter to run the script. The second line of the script contains the command for executing the Python script using the Python3 interpreter.
Step 3: Make the shell script executable
Before executing the shell script, it needs to be made executable. To do this, run the following command in your terminal:
1 |
chmod +x run_hello.sh |
This command changes the file permissions of the run_hello.sh script to make it executable by the user.
Step 4: Run the shell script
Now that the shell script is executable, you can run it by entering the following command in your terminal:
1 |
./run_hello.sh |
This command will execute the shell script, which in turn, executes the Python script. The output should display “Hello, World!” in your terminal.
Hello, World!
Full Code
Here is the complete code for the Python script (hello.py) and the shell script (run_hello.sh).
hello.py:
1 |
print("Hello, World!") |
run_hello.sh:
1 2 |
#!/bin/bash python3 hello.py |
Conclusion
In this tutorial, we walked through the process of running a Python script from a shell script. This technique allows you to combine the power and flexibility of Python with the convenience of shell scripting, enabling you to automate tasks and integrate Python into a broader scripting environment.