
Master Python Script Execution on Ubuntu with Python3 and Virtual Environments
Introduction
Running Python scripts on Ubuntu requires more than just typing out commands—it’s about managing dependencies, ensuring compatibility, and optimizing your development environment. With Python 3 and virtual environments, you can streamline your workflow and avoid conflicts between different versions of Python. This article will guide you through setting up Python 3, creating scripts, managing packages, and troubleshooting common errors on Ubuntu. Whether you’re working with legacy systems or building new applications, understanding how to leverage virtual environments will help you maintain a clean, efficient development setup. Let’s dive into the process and master Python script execution on Ubuntu!
What is Virtual environments?
Virtual environments are isolated spaces where you can store the specific libraries and versions needed for a Python project. This helps prevent conflicts between different projects by keeping their dependencies separate, making it easier to manage multiple projects with different requirements.
Step 1 – How to Set Up Your Python Environment
So, you’ve got Ubuntu 24.04 up and running, and here’s the good news—it already comes with Python 3 installed by default! This means you usually won’t have to install it manually unless you’re dealing with something a bit special. But still, it’s always a good idea to make sure that Python 3 is properly set up on your system.
To do that, just open your terminal and type in this simple command:
$ python3 –version
When you run it, your terminal will show you something like “Python 3.x.x,” where the “x.x” represents the exact version of Python 3 that’s installed. If you see that, you’re all set! Python 3 is already there, ready for action.
But what if you don’t see that? Or maybe you get an error saying something like “command not found”? No worries—that just means Python 3 isn’t installed yet, but that’s not a big deal at all. All you need to do is install it with this command:
$ sudo apt install python3
This command will grab the latest version of Python 3 from Ubuntu’s software repository. It’ll only take a minute, and once it’s done, just run
python3 –version
Next up: pip. If you’re going to be working with Python (and let’s be honest, you probably will), you’ll need pip. It’s the tool that helps you easily manage Python libraries and packages. You’ll be using it to install things like numpy, scikit-learn, and anything else your project needs. To install pip, just run:
$ sudo apt install python3-pip
Once pip is installed, you’ll be able to use it to easily download and manage Python packages. Now you’re all set! Your Python 3 environment on Ubuntu is good to go, and you’re ready to start coding.
For more details, check out the Ubuntu Python 3 Installation Guide.
Step 2 – How to Create Python Script
Alright, now that we’ve got everything set up, it’s time to get our hands dirty and start writing some Python code! This is where the fun really begins. First, you’ll want to head to the folder where you want to save your script. Think of this like picking the spot on your computer where you’re going to keep all your important files. To do that, simply run this command in the terminal:
$ cd ~/path-to-your-script-directory
Once you’re in the right place, it’s time to create a Python script. But how do you actually make a new script? Don’t worry, it’s simple—we’re going to use the nano text editor. It’s super easy to use. Just type this command in the terminal:
$ nano demo_ai.py
This will open up the nano editor, giving you a fresh blank text file to work with. Now you’re all set to write your Python code. You can either write your own from scratch or copy the example I’m about to show you. Here’s a simple script to get you started:
from sklearn.tree import DecisionTreeClassifier
import numpy as np
import random</p>
<p># 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</p>
<p># Create and train the model
model = DecisionTreeClassifier()
model.fit(x, y)</p>
<p># 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"</p>
<p>if __name__ == "__main__":
num = random.randint(0, 20)
result = predict_odd_even(num)
print(f"The number {num} is an {result} number.")
At first glance, this might look a bit complicated, but let me walk you through it. The purpose of this script is pretty simple: it predicts whether a number is odd or even. But how does it do that? Well, it uses something called a DecisionTreeClassifier from the scikit-learn library—a tool that helps the script “learn” from data. Here’s what’s going on in the script:
- Data Generation: x is a list of numbers from 1 to 20. We’ll use these numbers as input for our machine learning model. y contains labels for each number: 0 for even numbers and 1 for odd numbers. So, for example, the number 2 gets labeled with a 0 (because it’s even), and the number 3 gets labeled with a 1 (because it’s odd).
- Model Creation and Training: We create a DecisionTreeClassifier and train it using the x and y data. This helps the model figure out how to predict whether a number is odd or even.
- Prediction Function: The predict_odd_even(number) function takes a number as input and uses the trained model to predict whether that number is odd or even. It uses the model.predict() method to make that prediction.
- Random Number Generation: In the __main__ part of the script, we generate a random number between 0 and 20 using random.randint(0, 20). This is where the magic happens! The script then predicts whether that number is odd or even and prints the result.
Running the Script: Once you’ve written your code, don’t forget to save it! In nano, press CTRL + X, then hit Y to confirm saving, and finally, hit Enter to exit the editor.
This script is a basic example of how you can use machine learning in Python to classify data. It’s not just about simple math—it’s about teaching a model to spot patterns, like figuring out whether a number is odd or even. And the best part? You can take this idea and apply it to much more complex problems down the road!
Scikit-learn: Classifier Comparison
Step 3 – How to Install Required Packages
Alright, now we’re getting into the fun part—installing the packages that will bring your script to life! One of the most important packages you’ll need is NumPy . It’s a powerful library that’s super useful when it comes to creating and working with datasets. In the script we worked on earlier, NumPy was used to generate the dataset for training the machine learning model. Without it, things would get a bit tricky!
Here’s the deal: starting with Python 3.11 and pip version 22.3, there’s a change in how Python environments are handled. It’s called PEP 668 , and it introduces the idea of marking Python base environments as “externally managed.” What does that mean for you? Well, if you try to install packages using pip3 in certain environments, you might run into an error like “externally-managed-environment.” For example, if you run this command:
$ pip3 install scikit-learn numpy
You’ll get an error instead of the expected result. Frustrating, right? But don’t worry, there’s a fix!
To get around this, you’ll need to create a virtual environment. Think of it as your own little isolated space where you can install Python packages without messing with the system-wide Python setup. It’s like having your own personal workspace, where you can keep things neat without affecting anyone else’s work.
Let’s walk through how to set up that virtual environment:
Installing virtualenv
First, you need to install virtualenv , which is the tool that lets you create and manage these isolated environments. To install it, run this simple command:
$ sudo apt install python3-venv
Once that’s done, you’re all set to create a virtual environment in your project directory.
Creating the Virtual Environment
To create your environment, run this command:
$ python3 -m venv python-env
This will create a new directory called python-env in your current directory. Inside this folder, you’ll have a fresh Python environment—clean, neat, and ready to go.
Activating the Virtual Environment
Next, let’s get that environment activated so it can start doing its thing. Run this command:
$ source python-env/bin/activate
Once you do that, something cool happens: your terminal prompt will change. You’ll see the name of your virtual environment in parentheses, like this:
(python-env) ubuntu@user:~
This is your visual cue that you’re now working within your isolated environment. From here on out, any packages you install or commands you run will stay separate from the system Python setup. You’re in your own little world now—perfect for managing dependencies and avoiding conflicts.
Installing the Required Packages
Now that your environment is up and running, let’s get those packages installed! To install scikit-learn and NumPy , which are crucial for machine learning tasks, run:
$ pip install scikit-learn numpy
scikit-learn is essential for data mining, machine learning, and data analysis. It’s a must-have for any data science project.
NumPy helps with handling arrays and numerical data, making complex calculations and data manipulations a breeze.
And here’s a little bonus: You don’t even need to install the random module. It’s already part of Python’s standard library, so it’s good to go by default.
Why Is This Important?
Setting up a virtual environment and installing the required packages this way is a best practice in Python development. It ensures your environment stays isolated, so it doesn’t mess with other projects you’re working on. Plus, it’s super helpful when you need different versions of packages or Python for other projects. This approach keeps everything organized, clean, and hassle-free.
By following these steps, you’ve successfully set up your own isolated Python environment, installed all the packages you need, and ensured everything is running smoothly. Now you’re all set to dive into your project with a clean and well-managed workspace!
For a more detailed explanation on Python Virtual Environments, check out the full guide here.
Step 4 – How to Run Python Script
Alright, you’ve done the tough part—setting up your virtual environment and installing all the packages you need. Now it’s time for the fun part: running your Python script and seeing everything come to life!
To start, head over to the folder where you’ve saved your Python script. If you’re not quite sure where that is, just use the terminal to navigate there. Once you’re in the right place, you’re all set to run the script. All you have to do is type this command:
$ python3 demo_ai.py
This command tells your Ubuntu system to run the script using Python 3. If everything’s set up correctly, the script will run, and you’ll see the output right in your terminal. It’s like flipping a switch and watching everything work!
For example, when you run the script, you might see something like this:
(python-env) ubuntu@user:~/scripts/python demo_ai.pyThe number 5 is an Odd number.
In this case, the script randomly picked the number 5, and based on the machine learning model you trained earlier, it correctly predicted that 5 is an odd number. Cool, right?
Now, here’s where it gets even cooler. If you run the script again, you’ll probably get a different result. For example:
(python-env) ubuntu@user:~/scripts/python demo_ai.pyThe number 17 is an Odd number.
This shows off the randomness in action! The random.randint() function is generating a new number each time the script runs, and then it gets classified as either odd or even based on the decision tree model you created.
This isn’t just about seeing the same thing again and again—it’s about your script using a trained machine learning model to make predictions. Every time you run it, you get a fresh random number, and the model figures out whether it’s odd or even. Pretty cool, right?
By following these steps, you’ve successfully run your first Python 3 script, brought machine learning to life, and seen how your model classifies numbers. This is the magic of using virtual environments and Python—everything is isolated, clean, and ready for more advanced tasks!
For more information on Python basics, check out the Beginner Python Tutorials.
Step 5 – How to Make the Script Executable [OPTIONAL]
Alright, you’ve done all the hard work—your script is set up, your virtual environment is running smoothly, and Python 3 is installed. But here’s the thing: you can make your Python script even more efficient by making it executable. It’s totally optional, but trust me, it’s a cool little hack that saves you time and effort.
Once your script is executable, you won’t have to type python3 demo_ai.py every time you want to run it. Instead, you can just run the script directly from the terminal, just like any other command. Pretty awesome, right? Let’s walk through how to do it.
Open the Python Script
First, you’ll need to open your Python script in a text editor. You can use the nano text editor for this. Just run the following command in your terminal:
$ nano demo_ai.py
This opens up the script in nano, where you can make changes.
Add the Shebang Line
Here’s the magic step: at the very top of your script, you need to add a shebang line. This is a special line that tells your operating system which interpreter to use when running the script. Since we’re using Python 3, you’ll need to add this line as the very first thing in the file:
#!/usr/bin/env python3
This tells the system, “Hey, use Python 3 to run this script,” no matter where Python 3 is installed on your machine.
Save and Close the File
Once you’ve added the shebang line, it’s time to save your work. In nano, do this by pressing CTRL + X to exit the editor. Then, press Y to confirm that you want to save the changes, and hit Enter to finalize it. Boom, your file is saved!
Make the Script Executable
Now for the fun part: making your script executable. This step is all about changing the file’s permissions so it can be run directly. To do that, run this command in your terminal:
$ chmod +x demo_ai.py
What this does is grant your script execute permissions, meaning it’s now ready to run just like any other command in your terminal.
Run the Script Directly
Now that your script is executable, you can skip the python3 part entirely. Instead of typing:
$ python3 demo_ai.py
You can simply run the script like this:
./demo_ai.py
That’s it! When you run this command, your script will execute, and you should see the same output as before. The Python 3 interpreter will still be used, thanks to the shebang line you added.
Why Bother?
By making your script executable, you’ve just streamlined the process. It’s a small change that saves you from typing python3 every time you run the script. It’s quicker, easier, and just feels more natural when working with your Python scripts. Plus, it’s one of those little touches that make coding feel more like a smooth, efficient workflow.
So, now you’ve got a Python script that runs with just a single command. It’s one more step toward making your development process faster and more convenient—just the way we like it!
How to Make a Python Script Executable on Linux
How to Handle Both Python 2 and Python 3 Environments
Imagine you’re juggling two different versions of Python—one foot in the past, the other in the future. That’s what it’s like managing both Python 2 and Python 3 on your Ubuntu system. It’s like trying to fit two different puzzle pieces into the same frame. But, don’t worry, you can totally make it work.
The key to managing these two Python versions is simple: use clear commands when running scripts and set up virtual environments for your projects. This way, you stop the versions from stepping on each other’s toes. No more conflicts between packages and dependencies. By isolating each project in its own virtual environment, you can easily switch between Python versions without worrying about them interfering with each other.
Before we dive deeper into the setup, here’s something important to keep in mind: Python 2 is officially obsolete. It hasn’t received any updates since 2020, and it’s no longer supported. No security patches, no bug fixes—it’s like an old car that you keep driving around but isn’t really safe anymore. For any new projects, you definitely want to use Python 3 and virtual environments (venv). You can reserve Python 2 only for those old, legacy projects that still need it.
How to Identify System Interpreters
Now, let’s see what’s on your system. To check if you’ve got both Python 2 and Python 3 installed, you can easily check by running a couple of commands in the terminal.
First, check for Python 3 by typing:
$ python3 –version
This will show you the version of Python 3 installed on your system. If it’s installed, you should see something like Python 3.x.x (where “x” represents the version number).
Then, check for Python 2 by running:
$ python2 –version
If the terminal responds with something like “command not found,” it means Python 2 isn’t on your system anymore or it’s been removed. In that case, you’re only working with Python 3, and you can just focus on that.
How to Explicitly Run Scripts
Now that you know what versions of Python are available, it’s time to get to the fun part—running your scripts! The trick to making sure your script runs with the right version is to be clear about which one you’re using.
If you want to run a script with Python 3, just type:
$ python3 your_script_name.py
If, for some reason, you’re still working with Python 2, use:
$ python2 your_script_name.py
This way, there’s no confusion. Your system knows exactly which version to use, and you won’t run into compatibility issues. Simple, right?
How to Manage Projects with Virtual Environments (Best Practice)
Here’s the best way to handle your projects, especially if you’re switching between Python 2 and Python 3: use virtual environments. These are isolated spaces where you can store project-specific dependencies, separate from the global Python setup. This approach solves what developers call “dependency hell,” where projects need different versions of the same package and everything gets messy.
By using virtual environments, you can create separate, neat workspaces for each project, making sure that each one has the right dependencies—without any clashes.
How to Create a Python 3 Environment with venv
Creating a virtual environment with Python 3 is super easy, and the best part is that venv, the tool to create them, comes pre-installed with Python 3. But just in case it’s missing, here’s how you can get it:
First, you might need to install venv with the following commands:
$ sudo apt update
$ sudo apt install python3-venv
Once you’ve got that, let’s make your environment. To create a new virtual environment, just run:
$ python3 -m venv my-project-env
This will create a new directory called my-project-env , where all the magic happens. It’s like setting up a clean, isolated workspace for your project.
To get started with your environment, activate it by running:
$ source my-project-env/bin/activate
After you do this, you’ll notice that your terminal prompt changes. It will now show something like:
(my-project-env) ubuntu@user:~
This means you’re working within your virtual environment, and any Python or pip commands you run will only affect this project. Super neat, right?
How to Create a Python 2 Environment with virtualenv
If you’re dealing with a legacy project that requires Python 2, you’ll need the virtualenv package. This is just like venv for Python 3, but it’s made to work with Python 2.
Here’s how to set it up:
First, make sure you’ve got virtualenv, Python 2, and pip installed by running:
$ sudo apt install python3 python3-pip virtualenv
If you’re on Ubuntu 20.04 or later, you might need to enable the universe repository or manually download Python 2 if it’s not available through your package manager.
To create the Python 2 virtual environment, use this command:
$ virtualenv -p /usr/bin/python2 my-legacy-env
Once that’s done, activate your environment like this:
$ source my-legacy-env/bin/activate
Now, you’re inside your Python 2 virtual environment. The terminal prompt will let you know, and any Python commands will be executed with Python 2. If you’re done, just run:
$ deactivate
This will take you back to your global Python environment.
Understanding Shebang Lines
A shebang line is the first line in a script that tells the operating system which interpreter to use. Think of it like giving your computer a map to figure out how to run your script.
For Python 3, the shebang line should look like this:
#!/usr/bin/env python3
And for Python 2, it would be:
#!/usr/bin/env python2
Once you’ve added the appropriate shebang line, you need to make the script executable. This is done by changing the file permissions with:
$ chmod +x your_script.py
Now, instead of typing python3 your_script.py every time, you can simply run the script directly:
$ ./your_script.py
If you want to run your script from anywhere, move it to a directory in your system’s PATH, like /usr/local/bin . That way, you can execute it without being in the same folder.
With virtual environments, multiple Python versions, and shebang lines, you can keep your projects organized, avoid compatibility issues, and have everything running smoothly. It’s a bit of setup, but once it’s done, your workflow will be a lot more efficient!
Python Virtual Environments: A Primer
How to Identify System Interpreters
So, you’re diving into Python on your Ubuntu system, but you need to figure out which versions of Python are installed, right? Don’t worry, it’s pretty simple! Think of it like checking which tools you’ve got—are you working with the shiny, modern Python 3, or do you still have some Python 2 hanging around? Here’s how you can check and know for sure.
Checking for Python 3
The first thing you’ll want to do is confirm if Python 3 is installed. Luckily, it’s really easy to check. Just open your terminal and type:
$ python3 –version
If Python 3 is installed, you’ll see something like
Python 3.x.x
Python 3.8.5
Checking for Python 2
Now, let’s check for Python 2. If you’re working with older projects, you might still need this version. To see if it’s installed, run:
$ python2 –version
If Python 2 is around, this command will show you the version number, like
Python 2.7.18
What Does This All Mean?
Here’s where it gets important. If you run the
python2
By running these commands, you’ll quickly figure out what you’ve got on your system. It’s like checking your toolkit before you get to work—once you know what’s available, you can be sure you’re using the right Python version for your project.
For more information, you can refer to the Install Python 3 on Ubuntu tutorial.
How to Explicitly Run Scripts
Alright, so you’ve got your Python script ready to go, but there’s one thing you need to make sure of: you’re running it with the right version of Python. It might seem like all you have to do is type python your_script.py , but here’s the thing—if you’ve got both Python 2 and Python 3 on your Ubuntu system, the default command might not always point to the version you expect. That’s where being specific comes in. You can take control and make sure the right interpreter runs your script. Let’s break it down!
Running a Script with Python 3
To run your script using Python 3, all you have to do is tell your terminal exactly what you want by typing:
$ python3 your_script_name.py
Now, this is super important: always use python3 instead of just python . On many systems, python might still point to Python 2, especially if both versions are installed. Using python3 ensures that Python 3 is running the script, so you won’t run into any unexpected issues. It’s like telling your computer, “Hey, I’m using Python 3—no surprises!”
Running a Script with Python 2
But what if you need to run your script with Python 2? Maybe you’re maintaining an old project that still relies on Python 2. Even though Python 2 is now outdated, you can still make it work with a simple command:
$ python2 your_script_name.py
This command will run your script with Python 2—if it’s installed, of course. Just keep in mind, Python 2 isn’t officially supported anymore. So, you’re really only using it if you absolutely have to, like with legacy projects that can’t be upgraded. For anything new, Python 3 should be your go-to.
Why Being Explicit Matters
By explicitly specifying which version of Python to use, you’re making sure your script runs smoothly every time. This method helps you avoid any potential conflicts, making sure you don’t run into version mismatches. After all, you don’t want to be left wondering why your script behaves differently depending on the environment, right?
So, by controlling which version runs your code, you can keep things clean, predictable, and ready for anything!
Always ensure you’re using the correct version for consistency and compatibility across systems.
How to Manage Projects with Virtual Environments (Best Practice)
Imagine you’re juggling multiple Python projects—one project needs a specific version of Python, while another might require completely different libraries or even a different version of Python. Without a clear structure in place, things can get messy really fast. This is where virtual environments come to the rescue.
A virtual environment is like creating a separate, self-contained world where you can set up exactly what you need for a project, without it interfering with other projects or the global Python setup on your Ubuntu system. Think of it as having different rooms for each of your projects, each one with its own set of tools and resources. This way, you avoid “dependency hell,” which happens when two projects need different versions of the same library, and everything starts falling apart. Virtual environments make sure everything stays neatly organized, so each project can thrive without stepping on the toes of another.
How to Create a Python 3 Environment with venv
The venv module is built right into Python 3, and it’s the easiest and best way to create these isolated environments. It’s simple to use and ensures your projects stay organized. Let’s walk through the steps!
Install venv (if needed) If you don’t already have venv installed, don’t worry—it’s really easy to set up on Ubuntu. Just open up your terminal and run these commands to get venv ready:
$ sudo apt update
$ sudo apt install python3-venv
This will install venv on your system.
Create the Virtual Environment Once venv is installed, creating a virtual environment is really easy. In your terminal, run:
$ python3 -m venv my-project-env
This command will create a new folder called my-project-env in your current directory. Inside this folder, you’ll find a fresh Python 3 interpreter and all the libraries you need for your project—completely separate from anything else on your system. Think of it as setting up a clean workspace just for this project.
Activate the Virtual Environment Now for the fun part! To start using your virtual environment, you need to activate it. Run this command:
$ source my-project-env/bin/activate
Once activated, you’ll notice your terminal prompt changes to show the name of your virtual environment, like this:
(my-project-env) ubuntu@user:~/your-project-directory$
This means you’re working within your virtual environment, and any Python or pip commands you run will now use the Python 3 interpreter inside the my-project-env environment. You’re all set to start working on your project, without worrying about messing with other environments.
How to Create a Python 3 Environment with virtualenv
If you’re working on a legacy project or just want more flexibility, you might want to use virtualenv instead of venv. virtualenv is a third-party tool that gives you extra features, especially when you need to manage Python 2 environments. Here’s how to set it up:
Install Prerequisites Before you can use virtualenv, make sure Python 3, pip, and the virtualenv package are installed. Run these commands:
$ 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 manually download Python 2 if it’s not available via the package manager.
Create the Virtual Environment with Python 2 If you’re maintaining an old project that needs Python 2, you can still use virtualenv to create a Python 2 environment. Run this command:
$ virtualenv -p /usr/bin/python2 my-legacy-env
This will create a virtual environment called my-legacy-env that uses Python 2 as its interpreter. Cool, right?
Activate the Virtual Environment Once your environment is set up, you’ll need to activate it:
$ source my-legacy-env/bin/activate
Now, when you look at your terminal prompt, you’ll see the environment name, like this:
(my-legacy-env) ubuntu@user:~/your-project-directory$
This means you’re working inside your Python 2 virtual environment. All your python and pip commands will now use Python 2.
Deactivate the Virtual Environment When you’re done with your project and want to leave the virtual environment, you can deactivate it by typing:
$ deactivate
This will take you back to your system’s default Python environment.
Wrapping It All Up
Whether you’re using venv for Python 3 or virtualenv for legacy Python 2, virtual environments are a game changer. They let you keep your projects isolated, ensure your dependencies are clean, and make sure you’re always using the right version of Python. This practice saves you time, helps avoid frustration, and keeps everything running smoothly while juggling multiple projects. You’ll never have to worry about breaking things again, as long as you’re working within your own, neat environment!
Python Virtual Environments: A Primer
How to Create a Python 3 Environment with venv
Imagine you’re juggling multiple Python projects on your Ubuntu system. One project needs a specific version of a library, while another requires something completely different. Without a solid plan in place, these conflicting dependencies could cause all sorts of issues with your workflow, right? That’s where venv comes to the rescue. The venv module, built right into Python 3, is the key to creating these isolated project environments. Think of it as a separate workspace for each of your projects. You can experiment safely, install different versions of libraries, and work on multiple projects without worrying about them interfering with each other or the global Python environment on your Ubuntu system. Let’s walk through how to get it set up.
Install venv (if needed)
In most cases, venv is already installed with Python 3, so you’re good to go. But just in case it’s not there, it’s easy to install. First, make sure your system is up to date by running:
$ sudo apt update
Once that’s done, install venv with this command:
$ sudo apt install python3-venv
Now, venv is all set to create isolated environments for you. It’s like having a fresh toolbox for each project—organized, neat, and free from interference.
Create the Virtual Environment
Now that venv is set up, it’s time to create your virtual environment. It’s super simple. First, go to the directory where you want to store your project, and then type:
$ python3 -m venv my-project-env
This will create a new folder called my-project-env in your current directory. Inside, you’ll have a fresh Python 3 environment, completely separated from the system’s global Python setup. You can name the environment whatever you like, but my-project-env works perfectly for now.
Activate the Virtual Environment
Now that you’ve created the environment, it’s time to activate it and step into your isolated workspace. Just run this command:
$ source my-project-env/bin/activate
Once activated, your terminal prompt will change to show the name of your virtual environment, like this:
(my-project-env) user@hostname:~/project-directory$
This small change in your terminal means you’re now working within the virtual environment. From here on out, every time you run Python or install packages, it’ll happen inside this environment—no worries about affecting anything else on your system.
Using Python and pip in the Virtual Environment
Now that you’re in your environment, you can install libraries or run your Python scripts, and all dependencies will be safely contained within this space. For example, to install NumPy, which is a great library for numerical computing, run:
$ pip install numpy
This will install NumPy inside your virtual environment, leaving your system’s Python untouched. When you want to run a script, just execute:
$ python my_script.py
Your script will use the Python 3 interpreter from the environment, not the global version. It’s like having a bubble of clean code, keeping everything separate and organized.
Why Use venv?
So, why should you care about using venv? Here’s the deal: venv is a game-changer for Python developers. It ensures each project has its own dependencies. No more worrying about different projects needing different versions of the same library. No more stress about global packages messing up your work. It keeps things tidy, organized, and—best of all—reliable.
By isolating each project in its own virtual environment, you create a clean, reproducible development setup. You’ll spend less time fixing errors and more time doing what you love: writing great Python code.
In short, venv gives you the tools to keep your projects organized, avoid compatibility issues, and make sure your development process stays smooth. Pretty handy, right?
Python Virtual Environments: A Primer
How to Create a Python 3 Environment with virtualenv
Imagine you’re managing an old application stuck on Python 2, or maybe you just need full control over which version of Python your project uses. That’s where virtualenv steps in. Think of it like creating a little sandbox for your projects, where you can decide exactly what version of Python and which libraries your project needs, without anything interfering with other projects or your system-wide installations.
Now, if you’re familiar with Python 3’s built-in venv, you might wonder why you’d use virtualenv. Well, here’s the deal: virtualenv is your go-to tool when you need more flexibility. It allows you to specify the exact Python version you want, which is perfect if you need Python 2 for legacy applications or if you want to have more control over your environments than what venv offers. Ready to dive in? Let’s get started!
Steps to Set Up a Python 2 Virtual Environment with virtualenv
Install Prerequisites
Before you can use virtualenv, you need to have a few things in place. First, you’ll need Python 3 and pip (the package manager for Python) installed on your system. Then, you can install virtualenv, the tool that helps you create and manage isolated environments. Don’t worry, it’s an easy setup. Here’s how to get everything ready:
sudo apt install python3 python3-pip virtualenv
With these commands, you’ll have Python 3, pip, and virtualenv installed. Now, a heads-up: Ubuntu 20.04 and later may not include Python 2 in the default package manager. If that’s the case, you might need to enable the universe repository or manually install Python 2. But no worries, we’ll keep going!
Create the Virtual Environment
Now, here comes the fun part—creating the actual virtual environment. With virtualenv, you can choose exactly which version of Python you want for the environment. For this case, we’re going to use Python 2, which is perfect for legacy projects.
First, go to your project directory and run the following:
virtualenv -p /usr/bin/python2 my-legacy-env
In this command:
- The -p /usr/bin/python2 part tells virtualenv to use Python 2 for this environment.
- my-legacy-env is the name of the virtual environment you’re creating (you can name it whatever you like, but let’s keep it simple).
This will create a folder called my-legacy-env in your project directory. Inside, you’ll have a clean Python 2 environment, totally separate from the rest of your system.
Activate the Virtual Environment
Now that you’ve created the environment, it’s time to activate it and step into your own little workspace. Just run:
source my-legacy-env/bin/activate
Once you do that, your terminal prompt will change, and you’ll see something like this:
(my-legacy-env) user@hostname:~/project-directory$
This means you’re now inside the my-legacy-env virtual environment. Every time you run Python or pip commands, they’ll use Python 2 from within this environment, not the global Python setup. It’s like putting on a special pair of glasses to see things from a new perspective. Pretty cool, right?
Use Python and pip in the Virtual Environment
Now that you’re inside the environment, you can install packages or run Python scripts, knowing that everything is neatly contained within this space. For example, to install a package for your project, run:
pip install some-package
This installs the package directly into your my-legacy-env environment, leaving your system’s Python untouched. When you run Python scripts, they’ll use Python 2 from this environment:
python my_script.py
This way, your script uses exactly the version of Python and libraries it needs, without messing with your global setup.
Deactivate the Virtual Environment
When you’re done working within your virtual environment and want to return to the system’s default Python setup, just run:
deactivate
This takes you back to the system’s default Python environment. It’s like stepping out of your own sandbox and back into the regular playground. Now, your terminal will return to normal, and any future Python commands will use the global setup.
Why Use virtualenv?
You might be wondering, why bother with virtualenv in the first place? Here’s the deal: it helps you keep your projects organized and neat. For legacy Python 2 projects or when you need to control which Python version you’re using, virtualenv ensures that your dependencies don’t clash. It’s like keeping your Python 2 and Python 3 projects in separate rooms so they don’t argue over the same libraries.
By isolating your projects in their own environments, you can avoid the dreaded “dependency hell,” where different projects need different versions of the same package. And the best part? It’s all contained, organized, and easy to manage.
In short, virtualenv makes life easier when dealing with legacy systems, managing different Python versions, or juggling multiple projects. It’s a solid tool to help everything run smoothly and avoid compatibility headaches.
Make sure to refer to the official documentation for the latest updates.
Understanding Shebang Lines
So, here’s the situation: you’ve written an awesome Python script, and you’re excited to run it. But instead of typing the full command python3 your_script.py or python2 your_script.py every time, you want something quicker and smoother. That’s where the shebang line comes in, and it’s going to make your life a whole lot easier.
A shebang line is the very first line in your script file. It’s like telling your operating system (OS), “Hey, this is a Python script, and here’s how you should run it.” It saves you from typing out the Python command each time, letting you run your script directly.
Here’s how it works: you place the shebang line at the very top of your Python script, followed by the path to the Python interpreter. The best part? You get to specify which version of Python to use. Let’s break it down:
For Python 3, the shebang line should look like this:
#!/usr/bin/env python3
This tells your system, “Use Python 3 to run this script.” No matter where Python 3 is installed, it will always point to the right version.
Now, if you’re working on a legacy project that still relies on Python 2, you’ll need this:
#!/usr/bin/env python2
This makes sure your script runs with Python 2, which is perfect for those old applications that just won’t die (even though we might wish they would).
Making the Script Executable
Alright, you’ve got the shebang line in place. But here’s the catch: for it to work, you need to make your script executable. Think of it like giving your script permission to run on its own.
To do this, run a simple command in your terminal:
$ chmod +x your_script.py
This command is like telling your system, “Okay, now you can execute this script directly!” Now, instead of typing python3 your_script.py , you can just run it like this:
./your_script.py
Boom! The system knows exactly what to do, thanks to the shebang line, and you’ve made your life a lot easier. It’s like skipping the line at a concert and going straight to the fun stuff.
Running the Script Globally
Let’s take it up a notch. You don’t just want to run the script from the folder where it’s located—you want to be able to execute it from anywhere on your system. Here’s how to do that: move your script to a directory that’s part of your PATH.
The PATH is a list of directories your system checks when looking for executable files. So when you type a command, the system knows exactly where to look.
A common directory for user scripts is /usr/local/bin . To move your script there, run:
sudo mv your_script.py /usr/local/bin/
Now, your script is globally accessible, meaning you can run it from anywhere on your system. All you have to do is type:
your_script.py
No more navigating to the script’s folder—just type the script name, and let the shebang line and your PATH handle the rest.
By using the shebang line, making your script executable, and placing it in a directory within your PATH, you’ve just made running your Python scripts way easier. Whether you’re developing or deploying, this trick saves you time and effort, making script execution smoother and more efficient. It’s a small change that makes a big difference in your workflow!
Troubleshooting: Common Errors and Solutions
Let’s be honest—working with Python on Ubuntu (or really any system) can sometimes feel like solving a mystery. You’re typing away, making progress on your script, and then—boom!—an error message pops up, like a roadblock on your path. But here’s the thing: errors aren’t the enemy. They’re like clues that help guide you to the solution. With each error, you’re one step closer to figuring out what went wrong.
In this part of the journey, we’ll explore some common errors you might encounter while running Python scripts and how to fix them like a pro. Trust me, once you get the hang of these solutions, you’ll feel like part of the exclusive club of Python problem-solvers. These errors usually pop up because of file permissions, incorrect paths, or sometimes a little hiccup with your Python installation. Let’s dive in!
Permission Denied Error Message: bash: ./your_script.py: Permission denied
The Cause: Ah, the dreaded “Permission denied” message. It’s like showing up to a party and the bouncer won’t let you in because your name isn’t on the guest list. This happens when you try to run your script directly (like using ./your_script.py ), but the system says, “Nope, not today!” Why? Because your script doesn’t have “execute” permission. The operating system is stopping you from running the script for security reasons.
The Solution: No worries, you’ve got this. It’s easy to fix. You need to give your script permission to execute. You can do this using the chmod command, which is like saying, “Hey, it’s cool, you can run this script.” Here’s the magic command:
$ chmod +x your_script.py
This command gives your script execute permissions. After that, try running the script again with:
./your_script.py
And voilà! The “Permission denied” error is gone. Your script is now free to run.
Command Not Found Error Message: bash: python: command not found or bash: python3: command not found
The Cause: This one’s a classic. It happens when you try to run a Python script, but the system can’t find the Python interpreter. It’s like trying to call an Uber and not being able to find a driver. It’s not that the ride doesn’t exist, it’s just that the system can’t find it. This usually means Python isn’t installed or the Python executable ( python or python3 ) isn’t in your system’s PATH—the list of places the terminal looks for executable files.
The Solution: Time to get Python on board. To fix this, you’ll want to install Python 3, since it’s the version most people use now. Run these commands to install it:
$ sudo apt update
$ sudo apt install python3
Now Python’s on your system! But what if the terminal still won’t let you call Python by typing just python instead of python3 ? Don’t worry, there’s a fix for that too. You can install a package called python-is-python3 to make sure the python command points to Python 3:
$ sudo apt install python-is-python3
Once that’s done, double-check that it worked by running:
$ python3 –version
You should see the version of Python 3 installed on your system. Now your scripts are ready to go!
No Such File or Directory Error Message: python3: can't open file 'your_script.py': [Errno 2] No such file or directory
The Cause: This happens when you try to run a script that doesn’t exist in the current directory or you might have mistyped the file name. It’s like trying to walk into a room but realizing the door is locked. Happens to the best of us!
The Solution: First, make sure you’re in the right directory. You can check with the pwd command to see where you currently are in the system. This shows the “path” of your current directory. If you’re in the wrong place, just navigate to the correct directory with:
$ cd ~/path-to-your-script-directory
Next, list the files in your directory with:
$ ls
This will show you what files are there. Look for your script and double-check the spelling. If everything looks good, try running your script again.
If you’re in the wrong directory, no worries—just change to the right one using the cd command.
And there you go! These are some of the most common errors you might come across while working with Python on Ubuntu. They might seem intimidating at first, but with these solutions, you’ll be able to solve them in no time. And who knows? Every time you fix one of these errors, you’re leveling up in your journey to becoming a Python pro!
For more detailed guidance on the Ubuntu Command Line, check out the official tutorial.
Ubuntu Command Line Tutorial for Beginners
Conclusion
In conclusion, mastering Python script execution on Ubuntu with Python 3 and virtual environments is crucial for streamlining your development process. By setting up Python 3, creating isolated environments, and managing dependencies effectively, you can avoid common conflicts and ensure smooth script execution. Whether you’re handling legacy systems or working on modern projects, these best practices for Python and Ubuntu will help you maintain a clean, efficient workspace. Keep these methods in mind to tackle potential errors, enhance your coding efficiency, and keep your Python projects running smoothly. Looking ahead, virtual environments will continue to be a game-changer, offering greater flexibility and control as Python evolves.
Run Python Scripts on Ubuntu: Setup, Execution, and Best Practices (2025)