Tutorial

How to Run a Python Script on Ubuntu

Published on August 26, 2024

Technical Writer

How to Run a Python Script on Ubuntu

Introduction

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. For guidance on how to set this up, please choose your distribution from this list and follow our initial server setup guide. Please ensure to work with a supported version of Ubuntu.

  • Familiarity with the Linux command line. For an introduction or refresher to the command line, you can visit this guide on Linux command line primer.

  • 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.

Run Python Script on Ubuntu

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:

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:

sudo apt install python3

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

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:

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

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

nano demo_ai.py

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

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 the scikit-learn library. 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 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:

sudo apt install python3-venv

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

python3 -m venv python-env

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

source python-env/bin/activate

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

Output
(python-env) ubuntu@user:

Now, install the required packages by running:

pip install scikit-learn numpy

The random module is part of Python’s standard library, so you do not need to install it separately. It is included with Python and can be used directly without any additional installations.

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:

python3 demo_ai.py

Upon successful execution, you will see the desired output.

Output
(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.

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:

#!/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.

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:

./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.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar

Technical Writer

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.