Furthermore, it’s an object-oriented language that is packed with top-level data structures, dynamic binding, and dynamic typing. You can run it on all the most used systems like Windows, mac, and Linux. However, Linux users are unaware on how to execute the Python scripts on their devices. So, in this short blog, we will briefly explain how to run a Python script in Linux.
How to Run a Python Script in Linux
First, check the version of the currently installed Python in your system.
For Python2:
For Python3:
You can now run any Python script on your Linux device by merely entering the following given command:
Make sure that you replace the “script_name.py” with the name of the actual script that you want to execute. For example, let’s run the “hello_world.py” script.
This command runs the script and displays the result as shown in the following image:
Moreover, if you want to save this output in a separate text file, use the command as follows:
- Again, replace the “script_name.py” as you did in the earlier command.
- The “>” symbol forwards the resulting output to a text file.
- Replace the “file.txt” with the text file where you are saving the output. Remember, it directs the output to the specified file if it already exists in the current directory. Otherwise, it creates a new text file with your specified name to save the result.
For instance, if you want to direct the output to a file named “results.txt”, the command will be:
The command line does not display anything by default when you enter this command. Therefore, to check whether it has created the file, use the “ls” command.
As you can see at the bottom right of the previous image, the system creates the specified text file and stores the script’s output.
Similarly, you can also add the output of other Python scripts to the same file using double “>>” instead of single “>” in the previous command.
After running the previous command, you will see the two outputs inside the “result.txt” file. The “>>” expression instructs the systems to add/append to a particular text file.
Conclusion
Python scripts refer to the files containing Python codes. Everyone in the programming world needs to learn how to execute the Python programs and scripts in Linux systems. That’s why we explained about running a Python script in Linux in this guide. First, we discussed the command to run the scripts. Then, we demonstrated the methods of saving its output to the text files using simple examples.