Support Online
Skip to main content

Running Python Script in Ubuntu

Login

Running Python scripts on Ubuntu is a basic skill for many people, from software developers to system administrators, from data scientists to hobbyists.
Whether it's automating daily tasks, running a web server, or training a machine learning model, knowing how to run Python scripts correctly is essential.

In this article, we will take a comprehensive look at ways to run Python scripts on Ubuntu, from the simplest commands to pro tips.

In this article, we will show you step by step how to create your first script, starting from setting up your Python environment.
Among what you will learn:

  • Running script with python3 command,
  • Making scripts directly executable using the shebang line,
  • Establishing a virtual environment for different projects,
  • Managing version confusion on systems with both Python 2 and Python 3,
  • Identifying and solving common errors you may encounter.

Prerequisites 🔑

To follow this tutorial you will need:

  • A server running Ubuntu
  • A non-root user with sudo privileges
  • An active firewall

If you have not installed this environment yet, you can take a look at the First Server Installation with Ubuntu guide for step-by-step installation.

Also make sure that the version of Ubuntu you are using is a supported version.

  • Linux command line knowledge required.

Step 1 – Preparing the Python Environment

Ubuntu 24.04 comes with Python 3.
However, to be sure, open terminal and run the following command:

python3 --version

If Python 3 is already installed on your machine, the above command will display the current version.

If it is not installed, you can install Python 3 with the following command:

sudo apt-get install python3

In the next step, you need to install the pip package manager on your system.
Thanks to this tool, you can easily install and manage Python libraries.

To install, run this in terminal:

sudo apt-get install python3-pip

Step 2 – Creating Python Script ✍️

Now it's time to write the Python code you want to run.
To do this, first go to the folder where you will save your script:

cd /home/kullanici_adi/projelerim

You need to create a new file in your current directory.
To do this, type the following command in the terminal:

nano scriptim.py

This command will open a blank text editor.
You can write your own code here or copy the example below:

from sklearn.tree import DecisionTreeClassifier
import numpy as np
import random

# Örnek veri üret (1 ile 30 arasındaki sayılar)
X = np.array([[i] for i in range(1, 31)]) # 1'den 30'a kadar sayılar
Y = np.array([i % 2 for i in range(1, 31)]) # Çift = 0, Tek = 1

# Modeli oluştur ve eğit
classifier = DecisionTreeClassifier()
classifier.fit(X, Y)

# Sayının tek mi çift mi olduğunu tahmin eden fonksiyon
def sayi_tahmin(sayi):
sonuc = classifier.predict([[sayi]])
return "Tek" if sonuc[0] == 1 else "Çift"

if __name__ == "__main__":
rastgele_sayi = random.randint(1, 30)
tahmin = sayi_tahmin(rastgele_sayi)
print(f"{rastgele_sayi} sayısı {tahmin} olarak tahmin edildi.")

Step 3 – Installing Required Packages

In this step, we will install the packages we used in the script above.

First we need to install the NumPy library.
This library is useful for creating the data set we use to train our machine learning model.

Run this in terminal:

pip3 install numpy

In order to install and use NumPy without any problems, you first need to create a virtual environment.
This environment separates Python packages from the system environment, helping you manage the dependencies of different projects without mixing them.
This prevents package version conflicts and confusion.

As a first step, install the virtualenv tool:

sudo apt install python3-virtualenv

Now, you can create a virtual environment in your current working directory.

For example, to create an environment named venv:

python3 -m venv python-env

The next step is to activate the virtual environment you created.
To do this, run the activate script:

source python-env/bin/activate

When you run the command, you will see the name virtual environment at the beginning of the terminal line.
This indicates that the environment has been successfully activated.

Output example:

Output
(python-env) ubuntu@kullanici:

Now that the environment is active, you can install the necessary packages.

Run the following command:

pip install numpy scikit-learn

Step 4 – Running the Python Script ▶️

Now that all the necessary packages are installed, you can run your script.
To do this, use the following command in your working directory:

python3 scriptim.py

Once the command runs smoothly, you will see the expected output in the terminal.

Sample output:

14 sayısı Çift olarak tahmin edildi.

Step 5 – Making the Script Executable [Optional]

If you make your script executable, you won't need to type python3 every time.
In this way, you can run the script directly, it will be both faster and more practical.

First, open the Python script with a text editor:

nano scriptim.py

You need to add a shebang (a special line written at the very beginning of the script file) to the top line of the file.
This line tells which interpreter the system will use when running the script.

Add this to the first line of your script:

#!/usr/bin/env python3

After saving and closing the file, you need to make the script executable.
So you can run the script just like a normal command in the terminal.

Run the following command in terminal:

chmod +x scriptim.py

Once you run the script successfully, control will immediately return to you.
Now you can just run your script like this:

./scriptim.py

Troubleshooting: Common Errors and Solutions

Getting errors is a natural part of software development. You can think of this as your computer giving you a clue and asking you to solve the puzzle. 💡

Below are some common errors and solutions you may encounter in the terminal. These errors are usually related to permissions, file paths, or Python installation:

1. Permission Denied

Error Message:

bash: ./your_script.py: Permission denied

Reason:

  • You are trying to run a script directly, but there is no execute permission in the file. The operating system is blocking you for security purposes.

Solution:

  • Give execution permission to the file with the chmod (change mode) command:
chmod +x your_script.py

2. Command Not Found

bash: python: command not found

or

bash: python3: command not found

Reason:

  • Ubuntu cannot find the python or python3 interpreter. This means that Python is either not installed at all or is not defined in the system PATH variable.

Solution:

  • Install Python 3. This is the version that is standard in modern developments:
sudo apt update
sudo apt install python3

For convenience, you can also install a package that makes the Python command point to python3:

sudo apt install python-is-python3

3. No Such File or Directory

python3: can't open file 'your_script.py': [Errno 2] No such file or directory

Reason:

  • The script you are trying to run is not in the current directory or you typed the filename incorrectly.

Solution:

  • First, check whether you are in the correct directory with the pwd (print working directory) command.
  • Then, list the files in your directory with the ls command and make sure that the script name is written correctly.
  • If you are in the wrong directory, change to the correct directory using the cd command.

Result

In this article, you learned how to run Python scripts successfully on Ubuntu. Starting with the most basic python3 script.py command, we've seen how to make scripts directly executable with shebang and chmod.

Also:

The importance of virtual environments to professionally manage project dependencies,

How to act on systems with more than one Python version,

You've learned how to fix common errors you may encounter.

With this information, you are now equipped to run Python codes safely and effectively in all kinds of projects, from simple automations to complex applications.