Run Python Script Files Like the Bash Commands
Note: This blog only focuses on the Linux operating system(Unix like operating systems).
Python is a versatile programming language, sysadmins use Python for a lot of the tasks in their work. Typically, we use 'python'(or python3) command line tool to run the Python scripts. What if we want to run the Python scripts like bash commands? We'll see how to do it in this blog step by step.
1. Find the path of 'python'
We need Python interpreter to run the scripts. So first we need to find the path of 'python' command line tool. We can get the path by running the following command in Terminal.
2. Create a Python Script
We are going to create a Python script which will take the word or sentence from the command line and convert them to Upper Case. So create the text file without '.py' extension and name it as 'toupper'. Then add the following code in that file.
In the above example, see the first line (#! /usr/bin/python3), this is the key solution for our purpose. It denotes the following scripts will be executed by 'python3' command line tool.
3. Change the permission and Run.
Now we cannot execute the script file because our script file does not have the permission to execute. So we have to give the permission first. Use the ' chmod' command to change the permission of the file.
Now run the script
Great! See now our script file successfully running like an executable.
4. Configure in '.bashrc'
If we want to use this script file in other directories we need to configure in '.bashrc' file which is located in the home directory. Now get the path of our script file using the 'pwd' command.
Now add the following command in '.bashrc' file.
That's it! Now we can use that Python script from the command line for all directories.
Please comment below if this post need an improvement. Thanks for Reading!