Running programs is the first step in learning Python. Sure, there are great IDEs to run Python but what if you want to use the terminal only like most pro users do?
Well, in this tutorial, I will walk you through two ways to run Python programs in the Linux command line:
Using the python3 command (easy and recommended for new users):
python3 script.py
Running it as a script:
./script.py
So let's start with the first one.
Using the python3 command (easy)
This is the easiest way to run Python programs in Linux. Why?
Well, all you have to do is follow the given command syntax:
python3 <script.py>
For example, here's a simple Python program that takes input from the user and then prints a greeting message:
def greet():
# Prompt the user for their name
name = input("Enter your name: ")
# Greet the user
print(f"Hello, {name}! Welcome to the world of Python.")
# Call the greet function
greet()
I've saved this program as hello.py
so if I want to run it, then I have to use the following command:
python3 hello.py
As you can see, it asked for the input first and then used the input name to greet the user.
Running Python program as a script
If are familiar with how you run bash scripts in Linux and you want to use a similar approach then this is how you do it.
Things to remember while following this approach:
- The file will still have the
.py
extension not the.sh
. - You have to use the chmod command to make it executable.
- You're required to use
#!/usr/bin/python3
as a shebang.
Let's understand this with a simple example.
I will be using the same greetings program as I used to explain the usage of the python3
command.
First, I will use the nano text to create an empty file as shown:
nano hello.py
Now, I will write the following line of code:
#!/usr/bin/python3
def greet():
# Prompt the user for their name
name = input("Enter your name: ")
# Greet the user
print(f"Hello, {name}! Welcome to the world of Python.")
# Call the greet function
greet()
You will notice I have used the same code and the only difference is the shebang line used at the beginning of the line.
Once done, save changes and exit from the nano editor.
Next, make the file executable using the chmod command:
chmod +x hello.py
Finally, you can execute it the way you execute scripts in bash:
./hello.py
There you have it.
Here's more for Python programming
If you are not comfortable with the terminal usage and still want to learn Python then you can choose from the best Python IDEs for Linux:
And here are some resources to improve your Python knowledge.
I hope you will find this guide helpful.