How to Run a Python Script in a Linux Terminal

Python is a versatile programming language widely used for web development, artificial intelligence, machine learning, and other areas of coding. One of the easiest ways to run a Python script is through a Linux terminal. In this tutorial, we will walk you through the process of running a Python script in a Linux terminal, also known as the command-line interface.

Step 1: Prerequisites

Before we start, ensure you have a Python interpreter installed on your system. You can verify this by typing the following command into your Linux terminal:

If Python is installed properly, you should see the version of Python that is installed echo back to you. If not, refer to this guide to install Python.

Step 2: Create a Python Script

Let’s create a Python script called hello.py that prints out “Hello, World!”. You can create the file using a text editor of your choice in Linux.

Step 3: Write Python Code in the Script

Below is the Python code you need to write within your hello.py:

Step 4: Save and Exit

Once you’ve written your script, you next need to save and exit the editor.

Step 5: Run the Python Script

To run your Python script, you will use the python or python3 command followed by the name of your script:

Or, if you’re using Python3:

Sample Output

Hello, World!

Conclusion

Running a Python script in a Linux terminal is straightforward. It starts with creating a Python script file and then writing the Python code within. Finally, you execute the script using the Python command followed by the name of your file.