
Run Python Scripts on Ubuntu: A Step-by-Step Guide
Introduction
Style Guide:Subject Matter: A modern, clean illustration depicting the process of running Python scripts on Ubuntu. The focal point is a simplified, symbolic server or computer icon in the center, surrounded by abstract shapes representing code and virtual environments. The Python icon can subtly integrate into the design, symbolizing the running of Python scripts.Artistic Style: Flat design with minimalistic geometric shapes and smooth gradients. Use blue and yellow tones to create a professional yet vibrant atmosphere. The server is surrounded by abstract, wave-like lines that represent networks and the internet, adding a dynamic flow to the image.Color Palette: Soft blue for the background, with yellow tones to highlight central elements (like the server or Python script icon). Use gentle gradients for a modern feel and a clean, crisp look. Ensure the colors are balanced for a professional yet inviting vibe.Details and Lighting: Keep the lighting minimal, with subtle reflections on the central icons to enhance their modern, clean look. The design should maintain a sense of depth without heavy shadows or 3D effects. The icons and shapes should appear slightly elevated, using soft gradients to suggest light and shadow in a simple, non-distracting way.Perspective and Framing: The composition should feel slightly isometric to add depth while maintaining a flat, 2D aesthetic. The central server or computer icon should be in the foreground, with abstract shapes of code and environment layers extending outward in the background. The image frame should be 1024×1024 to ensure clarity and sharpness in digital use.Mood and Atmosphere: The overall atmosphere should feel professional, streamlined, and modern. The image should evoke a sense of clarity, order, and efficiency, symbolizing the ease of managing Python scripts on Ubuntu in a clean and organized digital workspace.
What is Python script execution on Ubuntu?
This solution explains how to run Python scripts on Ubuntu, covering the setup of the Python environment, creating scripts, managing dependencies with virtual environments, and executing scripts with commands or by making them directly executable. It provides steps for ensuring the correct Python version is used and how to handle common errors that may arise during execution.
Prerequisites
Alright, let’s get started on this! To follow along with this tutorial, you’ll need a server running Ubuntu, a non-root user with sudo privileges, and an active firewall. If you’re not sure how to set this up, no worries—I’ve got you covered with the “Initial Server Setup” guide for Ubuntu. It’s also super important that you’re using a supported version of Ubuntu. Make sure you’re on a recent version like Ubuntu 24.04, 22.04, or 20.04. If you’re still using Ubuntu 18.04 or earlier, it’s time to upgrade because those versions are no longer supported. A quick search can help you upgrade to the latest version, and trust me, you’ll want to do that for all the security and cool features. You’ll also need to be comfortable with the Linux command line. If you’re new to it, check out a guide on using the Linux command line—it’s a skill worth having. Once you’ve got that in place, open up your terminal and run this command to make sure everything’s up to date:
$ sudo apt-get update
This will ensure your system is running the latest versions and security updates from your repositories.
Run Python Script on Ubuntu
Now let’s dive into the fun part—running a Python script on Ubuntu. The journey has five simple steps:
- Set up the Python environment
- Create the Python script
- Install required packages
- Run the Python script
- Make the script executable
Don’t worry, we’ll go through each step together!
Setup Python Environment
First, let’s make sure Python 3 is ready to go. Ubuntu 24.04 comes with Python 3 installed by default, so you’re already halfway there. But let’s double-check to make sure it’s installed. Open your terminal and run this command:
$ python3 –version
If Python 3 is already installed, you’ll see the version number pop up. If it’s not, don’t worry! You can easily install it by running:
$ sudo apt install python3
Next, we’ll need the pip package installer. Pip is like a toolbox for Python—it helps you install all the extra packages you’ll need for your scripts. To install pip, run this:
$ sudo apt install python3-pip
Create Python Script
Now that Python is all set up, it’s time to create your script. First, navigate to the directory where you want to store your script:
$ cd ~/path-to-your-script-directory
Then, create a new Python file by typing this:
$ nano demo_ai.py
This will open up a blank text editor where you can write or paste your Python code. Here’s a simple script you can use:
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 decision tree classifier using the scikit-learn library. The classifier learns to predict whether a number is odd or even, based on randomly generated data. Once the model is trained, it makes a prediction for a randomly chosen number. After writing the script, don’t forget to save and exit the text editor.
Install Required Packages
Next up, we need to install the packages we’ll be using in the script. The first one is NumPy, which helps with working with numbers. Before we dive in, here’s a little tip: starting from Python 3.11 and pip 22.3, there’s a new rule called PEP 668. This rule marks Python environments as “externally managed,” which means that if you try installing packages like scikit-learn and numpy directly, you might run into an error unless you’re using a virtual environment.
So, to avoid that, let’s go ahead and create a virtual environment. This way, we can keep our Python packages separate from the system environment and avoid any conflicts later on. First, install the venv package by running:
$ sudo apt install python3-venv
Now, create the virtual environment by running this command:
$ python3 -m venv python-env
Activate it with:
$ source python-env/bin/activate
When you activate the virtual environment, your terminal prompt will change to show the name of your environment like this:
(python-env) ubuntu@user:
Now, you can install the required packages by running:
$ pip install scikit-learn numpy
The random module is part of Python’s standard library, so you don’t need to install it separately.
Run Python Script
With everything set up, you’re ready to run your Python script! Inside your working directory, type this command:
$ python3 demo_ai.py
Once you hit enter, you should see an output like this:
(python-env) ubuntu@user:~/scripts/python demo_ai.py The number 5 is an Odd number.
Make the Script Executable
[OPTIONAL] Here’s a cool trick: you can make the script executable, meaning you won’t need to type python3 every time you run it. To do this, open your Python script again with:
$ nano demo_ai.py
At the very top of the file, add this shebang line:
#!/usr/bin/env python3
Save and close the file. Then, make the script executable by running this:
$ chmod +x demo_ai.py
Now, you can run your script like any other command:
$ ./demo_ai.py
How to Handle Both Python 2 and Python 3 Environments
If you have both Python 2 and Python 3 installed on your system, it can be a bit tricky to manage. But don’t worry—it’s not too hard. Just use explicit commands for simple scripts and dedicated virtual environments for your projects. This way, you avoid version conflicts and package issues.
IMPORTANT NOTE: Python 2 is no longer supported and hasn’t received security updates since 2020. Always use Python 3 and venv for new projects. You should only use Python 2 if you absolutely have to for legacy apps.
How to Identify System Interpreters
If you want to check which versions of Python are installed and where your system’s python command is pointing, run these commands:
# Check for Python 3
$ python3 –version
# Check for Python 2
$ python2 –version
If you get a “command not found” error for Python 2, that means only Python 3 is installed.
How to Explicitly Run Scripts
You can control which version of Python runs your script by calling it directly. Here’s how:
- To run a script with Python 3: $ python3 your_script_name.py
- To run a script with Python 2: $ python2 your_script_name.py
How to Manage Projects with Virtual Environments (Best Practice)
Using a virtual environment is the best way to keep things organized. It creates a separate folder with its own version of Python and its own set of libraries, which helps prevent that dreaded “dependency hell,” where different projects clash over package versions.
How to Create a Python 3 Environment with venv
The venv module is built into Python 3 and is the go-to tool for creating virtual environments. To get started, first make sure venv is installed:
$ sudo apt update
$ sudo apt install python3-venv
Then, create and activate your virtual environment like this:
# Create the environment folder
$ python3 -m venv my-project-env
# Activate the virtual environment
$ source my-project-env/bin/activate
Once activated, your terminal prompt will change, and now the python and pip commands will automatically use the Python 3 interpreter.
How to Create a Python 3 Environment with virtualenv
For older projects, you might need the virtualenv package. To install it and set up an environment, run:
$ sudo apt install python3 python3-pip virtualenv
If you’re using Ubuntu 20.04 or later, you might need to enable the “universe” repository or download Python 2 manually if it’s not available. Create and activate the virtual environment with these commands:
# Create the environment, specifying the Python 2 interpreter
$ virtualenv -p /usr/bin/python2 my-legacy-env
# Activate the environment
$ source my-legacy-env/bin/activate
Once activated, the python and pip commands will point to Python 2. If you want to exit the environment, just run deactivate .
Understanding Shebang Lines
The shebang line is the first line in a script that tells the operating system which interpreter to use when running the script as an executable. For Python 3, it looks like this:
#!/usr/bin/env python3
For Python 2, it’s:
#!/usr/bin/env python2
To make sure the shebang works, you need to make the script executable by running:
$ chmod +x your_script.py
Now, you can run the script directly with:
$ ./your_script.py
And if you want to run it from anywhere, just move it to a directory in your PATH, like /usr/local/bin .
Troubleshooting: Common Errors and Solutions
Errors happen—it’s part of the process. Here are some common ones and how to fix them:
- Permission Denied
- Cause: You’re trying to run a script directly, but it doesn’t have the “execute” permission.
- Solution: Run this:
- Now you can run the script with:
- Command Not Found
- Cause: Ubuntu can’t find the Python interpreter.
- Solution: Install Python 3 by running:
- You can also install a package that makes the python command point to Python 3:
- No Such File or Directory
- Cause: You’re trying to run a script that doesn’t exist in your current directory, or you made a typo.
- Solution: Check if you’re in the right directory by running pwd (print working directory) and ls to list the files. If you’re in the wrong directory, use cd to go to the right one.
$ chmod +x your_script.py
$ ./your_script.py
$ sudo apt update
$ sudo apt install python3
$ sudo apt install python-is-python3
Initial Server Setup Guide for Ubuntu
Conclusion
In conclusion, running Python scripts on Ubuntu is a straightforward process once you understand the key steps involved. By setting up the Python environment, creating scripts, installing necessary packages, and managing dependencies with virtual environments, you can efficiently execute Python code. Whether you are using the python3 command or making your scripts executable with a shebang line, the flexibility of Ubuntu offers great advantages for Python developers. As you become more familiar with handling multiple Python versions and troubleshooting common errors, you’ll be well-equipped to take full advantage of Ubuntu’s powerful capabilities.Looking ahead, keeping up with Python updates and new virtual environment practices will continue to enhance your workflow, making Python on Ubuntu even more efficient and scalable in the future.Snippet for search results: Learn how to run Python scripts on Ubuntu with this easy-to-follow guide, including environment setup, script creation, and troubleshooting.
Master Python Script Execution on Ubuntu with Python3 and Virtual Environments