Run Python programs in Ubuntu command line
How To

How to Run Python Programs in Ubuntu Command Line

Sagar Sharma
Sagar Sharma

Table of Contents

If you thought nothing gets easier than learning Python, executing Python programs is even easier.

To run the python program, all you have to do is follow the given command syntax:

python3 Filename.py

And if you are running python2, you use only python instead of python3.

You may use dedicated IDEs like PyCharm for a more immersive Python coding experience, but this is sufficient for running a couple of Python scripts.

Let's see it in more detail.

Run Python program in Ubuntu command line

For your reference, I will be using the following Python code throughout this tutorial:

print('Hello Ubuntu users, greetings from sagar sharma')

Yes, that's a simple hello-world python program that is saved as hello.py in my system.

To execute the program, all you have to do is append the filename to the python3 command and that's it:

python3 Filename.py

As I mentioned earlier, I will be using hello.py so my command will be:

python3 hello.py
run python program in ubuntu

And that's it!

Run Python program as a script in Ubuntu command line

You might not want to use the python3 command just for executing the python program.

In that case, you can call the interpreter to do the work for you!

But to do so, you will have to make a slight change in your existing code.

You will have to add the following line at the beginning of your python code:

#!/usr/bin/env python3
run python program as script in ubuntu

Once you do that, you will have to make this file executable using the chmod command:

chmod +x Filename.py

And finally, you can execute the python program as a script:

./Filename.py
run python program as script in Ubuntu

And as you can see, the program was executed the same way as you execute shell scripts.

Want to learn Python for free?

Sure, there are a bunch of free tutorials on the internet but we handpicked the best for you!

You can refer to the following guide that contains some of the best (and free) Python courses and ebooks:

11 Free Courses and eBooks to Learn Python
Wondering how to learn Python for free? We list some of the best Python courses and books that you can use to learn Python online without spending any money.

I hope you will find this guide helpful.

And if you still have any doubts related to Python or anything else related to Linux, feel free to ask me in the comments.



Sagar Sharma

Sagar Sharma

A software engineer who loves to tinker with hardware till it gets crashed. While reviving my crashed system, you can find me reading literature, manga, or watering my plants.