Execute Python Scripts in Ubuntu

In this article, we would discuss how to execute Python scripts in Ubuntu. A Python script contains an instruction set. We save the Python script with .py extension.

The Python scripts can’t be compiled so, we can’t execute them. Therefore, we need to specify the command through which we can execute the file. This is where shebang comes to action. We write the shebang code in beginning of our Python script. There are two ways we can execute the Python script.

Let’s say we have a Python file – test.py. Usually, to compile and execute – we do the following –

python3 test.py

But, instead of executing the file this way, we can add shebang code to the file test.py.

Before that, we need to find the pathname for Python3 using which command-line utility. So, open a terminal and issue the following –

which python3

In our case, it returned with –

/usr/bin/python3

So, use a text editor like nano

nano test.py

and, add the following code in the beginning of test.py

#!/usr/bin/python3

and save the file.

Note: The above code may be different for you if the pathname is different. Therefore, make necessary changes accordingly.

Next, we need to make the file executable use chmod command-line utility –

chmod a+x test.py

Thereafter, to execute the file –

./test.py

In conclusion, we have discussed how to execute Python scripts in Ubuntu.