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 again. You should see that Python 3 is now installed and ready to go!
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
# 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.")
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.py
The 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.py
The 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 (where “x.x” represents the version number). For example, it might say Python 3.8.5, or whatever version you have. Thatâs your confirmation that Python 3 is good to go!
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. However, if Python 2 isnât installed, youâll get a “command not found” message, which means itâs not there anymore.
What Does This All Mean?
Hereâs where it gets important. If you run the python2 command and get an error, that means Python 2 is gone, and Python 3 is probably your only option. And honestly, thatâs becoming the standard these days. Since Python 2 reached its end of life in 2020, itâs no longer getting updates or security patches. Itâs like keeping an old smartphone that doesnât support new apps anymore. So, if you’re starting new projects, Python 3 is the way to go.
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/python2part tells virtualenv to use Python 2 for this environment. my-legacy-envis 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)

Leave a Reply