Run Python Scripts on Ubuntu: Setup, Execution, and Best Practices

Run Python Scripts on Ubuntu: Setup, Execution, and Best Practices

Introduction

Running Python scripts on Ubuntu is a powerful way to streamline development tasks and automate workflows. Whether you’re using the python3 command or setting up virtual environments to manage dependencies, knowing the best practices for execution is essential. In this guide, we’ll walk through the steps to set up your environment, create executable scripts with a shebang, and tackle common issues that might arise when working with both Python 2 and Python 3. By mastering these techniques, you’ll be able to run Python scripts on Ubuntu with confidence and efficiency, enhancing your productivity for various applications.

What is Running Python Scripts on Ubuntu?

This solution helps users execute Python scripts on an Ubuntu system. It explains how to set up the proper Python environment, use virtual environments to manage dependencies, and run Python scripts with basic commands or through a shebang. Additionally, it covers troubleshooting common errors and handling systems with both Python 2 and Python 3.

Step 1 – How to Setup Python Environment

Picture this: you’re all set to dive into Python coding on your shiny new Ubuntu 24.04 system. But before you jump in, let’s double-check that Python 3 is ready to go. Open up your terminal and type this command:


$ python3 –version

If Python 3 is already installed, you’ll see the version number pop up on your screen, and you’ll know you’re all set. If it’s not there, no worries! Just install it by running this command:


$ sudo apt install python3

Once that’s done, you’ll also need pip, which is the handy tool that helps you install Python libraries and dependencies. To grab pip, just run:


$ sudo apt install python3-pip

And there you go! Now you’re ready to roll with Python on Ubuntu.

Step 2 – How to Create Python Script

Next up, let’s create your first Python script! First, navigate to the directory where you want to store your script. If you’re unsure where that is, use this command to move to the right place:


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

Once you’re in the correct folder, create a new file by typing this command:


$ nano demo_ai.py

This will open up a blank text editor where you can start writing your script. Or, if you want to skip the blank canvas part, just paste this code into the file:


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.”)

Once you’re done, save the file and exit the editor. Now you’re ready to move on to the next step!

Step 3 – How to Install Required Packages

Now it’s time to install the Python packages you’ll need for the script, like NumPy and scikit-learn . But here’s the thing: starting with Python 3.11 and pip 22.3, there’s a new rule (PEP 668) marking base Python environments as “externally managed.” What this means is that if you try to install packages like scikit-learn or numpy , you might run into an error about “externally-managed-environment.” But don’t worry—there’s an easy fix!

What you need to do is create a virtual environment. Think of it like a special sandbox where all your project dependencies stay separate from your system’s Python. This helps prevent any conflicts with other projects.

To get started, first install virtualenv by running this command:


$ sudo apt install python3-venv

Then, create your virtual environment by running:


$ python3 -m venv python-env

To activate it, run:


$ source python-env/bin/activate

Once you do this, your terminal prompt will change to show that you’re inside the virtual environment.

Now, go ahead and install the packages you need for the script:


$ pip install scikit-learn numpy

By the way, the random module is built into Python, so you don’t need to install it separately.

Step 4 – How to Run Python Script

All set with the packages? Awesome! Now let’s run your Python script. Go to the directory where your script is saved and run it with:


$ python3 demo_ai.py

After running that command, you’ll see something like this pop up:

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

Or maybe something like this:

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

Everything’s working perfectly! Now you’re all set to start experimenting with Python.

Step 5 – How to Make the Script Executable [OPTIONAL]

Here’s a cool trick to make things even easier: let’s make your Python script directly executable. This way, you can just run the script without needing to type python3 each time.

Open your script with a text editor:


$ nano demo_ai.py

At the very top of the script, add a shebang line. This tells your system which interpreter to use when running the script. Add this line as the first line:


#!/usr/bin/env python3

Save and exit the file.

Next, make the script executable by running this:


$ chmod +x demo_ai.py

Once you’ve done this, you can now run your script directly like this:


$ ./demo_ai.py

How to Handle both Python 2 and Python 3 Environments

You might find yourself needing to work with both Python 2 and Python 3 on the same Ubuntu system. The best way to manage this is to use explicit commands for simple scripts and set up virtual environments for your projects. This way, you avoid confusion and conflicts between different Python versions.

Important Note: Python 2 is now officially obsolete, with no security updates since 2020. It’s best to stick with Python 3 and venv for all new projects. Only use Python 2 if you absolutely need to maintain older applications that can’t be upgraded.

How to Identify System Interpreters

To check which versions of Python are installed on your system and see where the python command points, run these commands:

For Python 3, run:


$ python3 –version

For Python 2, run:


$ python2 –version

If you get a “command not found” error when running python2 , it just means Python 2 isn’t installed on your system—only Python 3 is there.

How to Explicitly Run Scripts

Sometimes, you might need to be sure which version of Python is running your script. If that’s the case, you can directly call the Python version you want:

To run with Python 3, use:


$ python3 your_script_name.py

To run with Python 2, use:


$ python2 your_script_name.py

How to Manage Projects with Virtual Environments (Best Practice)

Think of a virtual environment like a personal workspace for your Python projects. It’s like creating a special folder where everything your project needs—including its own Python version and libraries—stays. By using virtual environments, you make sure that your different projects don’t mess with each other’s dependencies. This is known as preventing “dependency hell.” Using virtual environments is considered best practice for keeping your Python projects organized.

How to Create a Python 3 Environment with venv

The venv module is built right into Python 3, and it’s the go-to way to create virtual environments. Here’s how to set one up:

Install venv (if you haven’t already) by running:


$ sudo apt update
$ sudo apt install python3-venv

Now create and activate your virtual environment:


$ python3 -m venv my-project-env
$ source my-project-env/bin/activate

Once activated, your terminal prompt will change, and now Python and pip will automatically use the Python 3 interpreter and its package manager.

How to Create a Python 3 Environment with virtualenv

If you’re dealing with older projects that still require Python 2, you’ll need to use virtualenv . Here’s how to set up a Python 2 environment:

Install the necessary tools:


$ sudo apt install python3 python3-pip virtualenv

(Note: If you’re on Ubuntu 20.04+, you might need to enable the universe repository or manually install Python 2 if it’s not available through apt.)

Create and activate your Python 2 virtual environment:


$ virtualenv -p /usr/bin/python2 my-legacy-env
$ source my-legacy-env/bin/activate

Once inside the environment, the python and pip commands will now point to Python 2. To leave the environment and return to your normal shell, just run:


$ deactivate

Understanding Shebang Lines

A shebang is the very first line of your script, telling your system which interpreter to use when running the script.

For Python 3, use:


#!/usr/bin/env python3

For Python 2, use:


#!/usr/bin/env python2

To make this work, you’ll need to make the script executable:


$ chmod +x your_script.py

Now you can run your script directly with:


$ ./your_script.py

And if you want to run the script globally, just move it to a directory in your PATH, like /usr/local/bin .

Troubleshooting: Common Errors and Solutions

You might run into a few bumps along the way when running scripts. Here are some common errors and what they mean:

Permission Denied Error

Error:

Output
bash: ./your_script.py: Permission denied

Cause: This happens when the script doesn’t have the “execute” permission. Solution: Run this command to add execute permission:


$ chmod +x your_script.py

After that, run the script again with:


$ ./your_script.py

Command Not Found Error

Error:

Output
bash: python: command not found

Cause: This error occurs when Ubuntu can’t find the python or python3 interpreter. Solution: Install Python 3 with:


$ sudo apt update
$ sudo apt install python3

You can also install a package to make the python command point to Python 3:


$ sudo apt install python-is-python3

No Such File or Directory Error

Error:

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

Cause: This error means that the script doesn’t exist in the current directory. Solution: Check your directory with pwd (print working directory), and list the files with ls to confirm the script’s there. If you’re in the wrong place, use cd to go to the correct directory.

Conclusion

In conclusion, running Python scripts on Ubuntu is an essential skill for developers and system administrators alike. By following best practices like using the python3 command, managing dependencies with virtual environments, and creating executable scripts, you can significantly streamline your workflow. Additionally, understanding how to handle both Python 2 and Python 3 environments ensures compatibility across different systems and projects. As Python continues to evolve, staying up-to-date with the latest methods for execution and troubleshooting will help you maintain an efficient and reliable development environment on Ubuntu. With these practices, you’re well-equipped to maximize Python’s potential on Ubuntu for your projects and applications.

Run Python Scripts on Ubuntu: Master Virtual Environments and Execution

Alireza Pourmahdavi

I’m Alireza Pourmahdavi, a founder, CEO, and builder with a background that combines deep technical expertise with practical business leadership. I’ve launched and scaled companies like Caasify and AutoVM, focusing on cloud services, automation, and hosting infrastructure. I hold VMware certifications, including VCAP-DCV and VMware NSX. My work involves constructing multi-tenant cloud platforms on VMware, optimizing network virtualization through NSX, and integrating these systems into platforms using custom APIs and automation tools. I’m also skilled in Linux system administration, infrastructure security, and performance tuning. On the business side, I lead financial planning, strategy, budgeting, and team leadership while also driving marketing efforts, from positioning and go-to-market planning to customer acquisition and B2B growth.

Any Cloud Solution, Anywhere!

From small business to enterprise, we’ve got you covered!

Caasify
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.