How to run a Python file in Linux – Step by Step Guide

The Python file is a program file or script written in Python language. It can be created as well as edited with any text editor. In this tutorial, we will learn how we can run those python files in our Linux system.

Running a Python File In Linux

Step1: Write your own Python program in any basic text editor of your choice and save it with a .py extension.

Example:

print ("Hello!! You are now reading this Blog in CodeSpeedy.com")

Step2: Open the terminal emulator by pressing Ctrl+Alt+T.

Step3: Change or navigate to the directory where the Python file is saved using cd (Change Directory)  command.

Step4: Write the command to interpret or run the Python program on the terminal screen.

python3 filename.py

You can write in between python, python2, or python3 according to the version installed in your Linux system.

Output:

command to interpret or run the python program

An Alternative Method To Run a Python File

Step1: Add #! /usr/bin/python3 as the first line of the Python program.

Example:

#! /usr/bin/python
print ("Hello!! You are now reading this Blog in CodeSpeedy.com")

Step2: Open the terminal emulator by pressing Ctrl+Alt+T.

Step3: Make the file executable by running the following command:

chmod +x filename.py

Step4: Now type the commands to run the executable file.

./filename.py

Output:

How to run a Python file in Linux

Hope you enjoyed this tutorial and learned how to run a Python file in a Linux System easily.

Happy Coding!!!

You can also read, How to install Python on Linux – Step-by-Step Guide

Leave a Reply

Your email address will not be published. Required fields are marked *