Tutorials  /  Ubuntu

How to Run a Python Script on Ubuntu – Step-by-Step Guide

Ccentron Redaktion · March 2025 ·7 min read ·Ubuntu, Tutorial

As building AI-based tools becomes increasingly popular with developers, Python has emerged as one of the best programming languages for AI due to its simplicity, readability, and extensive libraries like TensorFlow, PyTorch, and scikit-learn. These libraries provide powerful tools for machine learning, data analysis, and neural networks, making Python a top choice for AI and machine learning projects.

Considering Python’s central role in AI, it’s important to learn how to run Python scripts effectively. This tutorial is designed to help you get started with running simple Python scripts on an Ubuntu machine, setting the foundation for more advanced AI scripting.

Prerequisites

To follow this tutorial, you will need:

  • A server running Ubuntu along with a non-root user with sudo privileges and an active firewall. Please ensure to work with a supported version of Ubuntu.
  • Familiarity with the Linux command line.

Before starting, run sudo apt-get update in the Ubuntu terminal to ensure your system has the latest versions and security updates for the software available from the repositories configured on your system.

These instructions are valid for the most recent versions of Ubuntu: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are using Ubuntu version <= 18.04, we recommend you upgrade to a more latest version since Ubuntu no longer provides support for these versions. This collection of guides will help you in upgrading your Ubuntu version.

VM

Matching infrastructure at centron

Ubuntu servers without your own hardware: ccloud³ VMs with full root access from €3.12 per month, billed by the hour and ready in seconds. Rent a cloud server →

Run Python Script on Ubuntu

  • Setup Python Environment
  • Create Python Script
  • Install Required Packages
  • Run Python Scripts
  • Make Script Executable

Step 1 - Python Environment Setup

Ubuntu 24.04 ships Python 3 by default. Open the terminal and run the following command to double-check Python 3 installation:

Console
python3 --version

If Python 3 is already installed on your machine, this command will return the current version of Python 3 installation. In case it is not installed, you can run the following command and get the Python 3 installation:

Console
sudo apt install python3

Next, you need to install the pip package installer on your system:

Console
sudo apt install python3-pip

Step 2 - Create Python Script

The next step is to write the Python code you want to execute. To create a new script, navigate to your directory of choice:

Console
cd ~/path-to-your-script-directory

When inside the directory, you need to create a new file. In the terminal, execute the following command:

Code
nano demo_ai.py

This will open up a blank text editor. Write your logic here or copy the following code:

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

# Generate sample data
x = np.array([[i] for i in range(1, 21)])  # Numbers 1 to 20
y = np.array([i % 2 for i in range(1, 21)])  # 0 for even, 1 for odd

# Create and train the model
model = DecisionTreeClassifier()
model.fit(x, y)

# Function to predict if a number is odd or even
def predict_odd_even(number):
    prediction = model.predict([[number]])
    return "Odd" if prediction[0] == 1 else "Even"

if __name__ == "__main__":
    num = random.randint(0, 20)
    result = predict_odd_even(num)
    print(f"The number {num} is an {result} number.")

This script creates a simple decision tree classifier using thescikit-learnlibrary. It trains the model to recognize odd and even numbers based on the randomly generated sample data. It then makes a prediction based on its learning for the given number.

Save and exit the text editor.

Step 3 - Install Required Packages

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

The first package you need to install is NumPy. You used this library to create a dataset for training the machine learning model.

Starting from Python 3.11 and pip 22.3, there’s a new PEP 668 that states the marking of Python base environments as “externally managed”. Which is why simply running pip3 scikit-learn numpy or similar NumPy installation commands will throw the error: externally-managed-environment.

To install and use NumPy successfully, you need to create a virtual environment that isolates your Python packages from the system environment. This is important because it keeps dependencies required by different projects separate and avoids potential conflicts between package versions.

First, install virtualenv by running:

Console
sudo apt install python3-venv

Now, use this tool to create a virtual environment inside your working directory.

Console
python3 -m venv python-env

The next step is to activate this virtual environment by executing the activate script.

Code
source python-env/bin/activate

On execution, you will notice the terminal prompt prefixed with your virtual environment name like this:

Output:

Code
(python-env) ubuntu@user:

Now, install the required packages by running:

Console
pip install scikit-learn numpy

The random module is part of Python’s standard library, so you do not need to in

Step 4 - Run Python Script

Now that you have all the required packages in place, you can run your Python script by executing the following command inside your working directory:

Console
python3 demo_ai.py

Upon successful execution, you will see the desired output.

Output:

Code
 (python-env) ubuntu@user:~/scripts/python demo_ai.py
The number 5 is an Odd number.
(python-env) ubuntu@user:~/scripts/python demo_ai.py
The number 17 is an Odd number.

Step 5 [OPTIONAL] - Make the Script Executable

Making the script executable allows you to run it directly without needing to explicitly call Python by typing python3. This makes running your script quicker and more convenient.

Open your Python script using a text editor.

Code
nano demo_ai.py

On top of the file, add a shebang i.e. #! line that tells the system what interpreter to use when executing the script. Append the following line before your code:

Code
#!/usr/bin/env python3

Save and close the file.

Now, make this script executable to allow it to run like any other program or command in your terminal.

Console
chmod +x demo_ai.py

On successful execution, you will see the control returned to you immediately. Starting now, you can simply run your script as follows:

Code
./demo_ai.py

Conclusion

Running Python scripts on an Ubuntu machine is a straightforward process. By understanding how to run Python scripts, you can begin exploring the powerful tools Python offers, including those essential for AI development.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Ubuntu
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren