
Run Python Scripts on Ubuntu: Master Virtual Environments and Execution
Introduction
Running Python scripts on an Ubuntu system can seem tricky at first, but with the right setup, it becomes a smooth process. By utilizing Python’s virtual environments, developers can easily manage dependencies and ensure their scripts run in isolated spaces, avoiding conflicts between different projects. This guide covers everything from setting up Python environments, creating and executing scripts, to solving common errors like “Permission denied” and “ModuleNotFoundError.” Whether you’re working with Python 2 or Python 3, mastering these tools on Ubuntu is essential for efficient Python development.
What is Running Python Scripts on Ubuntu?
This solution provides a step-by-step guide on how to execute Python scripts on Ubuntu. It explains how to set up the Python environment, create scripts, install necessary libraries, and manage dependencies using virtual environments. The guide also covers how to make scripts executable directly and addresses common errors such as permission issues. The goal is to help users run Python scripts effectively on Ubuntu systems.
Step 1 – How to Set Up Your Python Environment
So, you’ve got Ubuntu 24.04 installed and you’re excited to jump into some Python programming. The good news? Ubuntu 24.04 already has Python 3 installed, so you’re almost there! But here’s the thing—you might want to double-check and make sure everything is set up right. It’s always a good idea to confirm that everything’s in place before you start working on your projects. Now, don’t worry, this is easy. All you have to do is open up your terminal and run a simple command to check which version of Python is installed:
$ python3 –version
This will show you the version of Python 3 that’s installed on your system. If Python 3 is already good to go, you’ll see something like this:
Python 3.x.x
Great! If that’s the case, you’re all set and ready to go. But, if Python 3 isn’t installed yet—or if you see an error—you can easily install it. Just type this into your terminal:
$ sudo apt install python3
This will grab the latest version of Python 3 from the official Ubuntu repositories, and just like that, your system will be all set up with Python 3.
Alright, we’re not quite done yet. Next up is pip. No, not the little container you use for your coffee, but pip—the Python package installer. You’re going to need pip to manage all the libraries and dependencies for your projects. Installing it is just as easy. Run this command:
$ sudo apt install python3-pip
Boom! That’s it—pip is installed and ready to go. With Python 3 and pip set up, you’re now ready to start creating Python scripts and installing any packages you need. Whether you’re working on automation, web servers, or data science projects, you now have the foundation you need to start building with Python on Ubuntu.
You’re ready to roll—time to start coding your next big project!
Step 2 – How to Create a Python Script
Alright, now that you’ve got your Python environment set up and everything’s ready, it’s time to jump into writing your first Python script. This is where the real fun starts! The first thing you need to do is decide where you want to store your script, which means navigating to the right directory on your system. Don’t worry, it’s simple—just use the cd command in the terminal. Let’s say you want to store your script in a folder within your home directory. Here’s how you get there:
$ cd ~/path-to-your-script-directory
Once you run that, you’ll be in the folder you chose, ready to start working on your script. Next up, it’s time to create a new file for your Python script. You can use a text editor like nano, which is easy to use and works right in the terminal. To create a new script called demo_ai.py , type this:
$ nano demo_ai.py
This command will open up the nano text editor, and you’ll be staring at a blank canvas where you can start writing your Python code. If you’re following along with this tutorial, feel free to copy and paste the code I’m about to show you:
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.”)
Let’s Break Down the Code:
- Imports: First, we bring in the necessary libraries. We’re using DecisionTreeClassifier from sklearn.tree to create a decision tree model, numpy for handling numbers and arrays, and random to generate random numbers for predictions.
- Data Setup: Next, we create two arrays:
- x is an array of numbers from 1 to 20.
- y is an array where each number is labeled as either 0 for even or 1 for odd using a simple modulus operation.
- Model Creation: Then, we create a decision tree model ( model ) and train it using the sample data ( x and y ). The model learns to classify numbers as either even or odd based on the data it was trained on.
- Prediction Function: The predict_odd_even(number) function uses the trained model to predict whether a given number is odd or even. It takes a number as input, makes a prediction, and returns “Odd” if the prediction is 1 (odd) or “Even” if it’s 0 (even).
- Execution Block: Finally, in the if __name__ == "__main__": block, the script generates a random number between 0 and 20. It uses the model to predict whether that number is odd or even and prints the result.
Once you’ve typed out the code, it’s time to save and exit the editor. To do this in nano, press Ctrl + X to exit, then press Y to save the file, and hit Enter to confirm.
Now that your Python script is all set up, you’re ready to run it! This simple script shows you how to create a basic decision tree model that classifies numbers as odd or even. And this is just the start—you can tweak and build on this code for more complex tasks, like using different datasets or building more advanced models. The possibilities are endless!
Once you’ve saved your script, you can move on to the next step—running it. So, what are you waiting for? Let’s bring your Python script to life!
Decision Trees in scikit-learn
Step 3 – How to Install Required Packages
Alright, you’ve written your Python script, and now you’re itching to see it in action. But here’s the deal: to make it run, you need to install a few packages. The most important one is NumPy. If you’ve been following along, you used NumPy to create the dataset for training your machine learning model. It’s a must-have package for numerical computing in Python and super helpful when you’re working with data arrays and doing math. Without it, your project wouldn’t be complete.
However, with the release of Python 3.11 and pip 22.3, there’s a small change in how things work. The new PEP 668 has introduced a shift that marks Python’s base environments as “externally managed.” Basically, you can’t just install libraries directly into the global Python environment like you could before. So, if you try running commands like pip3 scikit-learn numpy , you might get an error saying “externally-managed-environment.” What’s going on is that your system won’t allow direct changes to the base environment anymore, thanks to the new way Python handles packages.
But don’t stress! There’s a simple fix for this. The solution is to create a virtual environment. Think of a virtual environment as a little self-contained world just for your project. It comes with its own Python installation and libraries, so it’s completely separate from your system environment. This is super useful, especially if you’re juggling multiple projects that need different versions of the same packages—it helps you avoid conflicts.
So, let’s get that virtual environment set up. First things first: you’ll need to install the python3-venv package, which has the tools you need to create these isolated environments. Run this command to install it:
sudo apt install python3-venv
Once that’s done, you’re ready to create your virtual environment. Just run this command in the terminal:
python3 -m venv python-env
Here, we’re calling our virtual environment python-env , but you can name it anything that makes sense for your project. This command will create a new folder with all the necessary files for your environment.
Next up: activating the environment. To do that, you’ll need to run the activation script:
source python-env/bin/activate
After running this, you’ll notice your terminal prompt changes to reflect that you’re now inside the virtual environment. It’ll look something like this:
(python-env) ubuntu@user:~$
That (python-env) at the start of the prompt shows you that your virtual environment is now active. Now, you’re in a safe zone where you can install packages without messing with your system’s Python setup.
To install the packages you need, like scikit-learn and NumPy, run this:
pip install scikit-learn numpy
These are the libraries that you’ll need for your script. scikit-learn helps you build the decision tree classifier, and NumPy takes care of the number crunching for your data.
One thing to
note:
With the virtual environment set up and all the packages installed, you’re ready to roll. You’ve isolated your project’s dependencies, making sure everything is in its right place. Now, it’s time to run your Python script and see it come to life, knowing that everything is set up and working smoothly.
PEP 668: Python Environment Management
Step 4 – How to Run Python Script
Alright, you’ve set everything up—you’ve installed all the necessary packages, created your virtual environment, and now you’re at the exciting part: running your Python script. But before we get into the fun part, let’s double-check that everything’s in the right place. Think of it like making sure you have all your stuff packed before heading on a trip.
First things first, you need to navigate to the directory where your Python script is. Let’s assume your script is in the ~/scripts/python folder. To get there, just type this into your terminal:
cd ~/scripts/python
Now that you’re in the right spot, it’s time to run your script. To do that, you’ll use Python 3 to execute the script. Just run this command:
python3 demo_ai.py
This tells your terminal to use Python 3—the version you’ve already set up—to run the demo_ai.py script. When you hit enter, you’ll see something awesome happen. Well, not magic, exactly, but close enough. If everything goes well, you’ll see something like this:
(python-env) ubuntu@user:~/scripts/python demo_ai.pyThe number 5 is an Odd number.
Here’s what’s happening: The script generates a random number—in this case, 5 —and uses the decision tree model you trained earlier to predict if the number is odd or even. Since 5 is odd, the script correctly prints, “The number 5 is an Odd number.” Pretty cool, right?
But wait, here’s the best part. You can run the script again and again, and each time, it will generate a new random number and predict whether it’s odd or even. For example, you run it again, and this time you see something like this:
(python-env) ubuntu@user:~/scripts/python demo_ai.pyThe number 17 is an Odd number.
It’s the same idea, but now with the number 17 . The script uses the trained decision tree model to predict whether the number is odd or even, and it does this perfectly every time, showing that everything is working as expected.
The exciting part here is that with Python 3, your virtual environment, and all the packages you installed, everything is running just like it should. Your script is now up and running, making predictions based on what the model has learned.
And the best part? You can always make it better! Want to predict more than just odd or even numbers? You can add more features to your script, like classifying numbers into different categories or even predicting more complex things. The possibilities are endless, and now you have the foundation to build on.
So go ahead, run that script again, and keep experimenting. With everything working, you’re one step closer to mastering Python on Ubuntu and diving deeper into machine learning. It’s time to see where your next line of code takes you!
For more details, refer to the Python Documentation.
Step 5 – How to Make the Script Executable [OPTIONAL]
So, you’ve written your Python script, and it’s working just fine. But here’s the thing: wouldn’t it be nice if you didn’t have to type python3 every time you want to run it? Wouldn’t it be easier if you could just treat it like any other program or command on your system? Well, good news—you can! Making your Python script executable means you can run it directly from the terminal without having to explicitly call Python each time. It’s like giving your script a VIP pass to run effortlessly.
Let’s break it down. Here’s how to make your Python script executable:
- Open the Python Script in a Text Editor: First things first—let’s get that script open. You’re going to need to make a small edit, so fire up your favorite text editor. If you’re using
nano
, which is super handy in the terminal, you can open your script with this command:
$ nano demo_ai.py
- Add the Shebang Line: Here’s the key part: at the very top of your script, you need to add a shebang line. Think of it as the script’s personal instruction manual, telling the operating system, “Hey, use Python 3 to run me.” For Python 3, this is what you add to the top of your
demo_ai.py
file:
#!/usr/bin/env python3
This line is super important. It ensures that your script will run with Python 3, no matter where Python is installed on the system. The env part is smart—it’ll find Python 3 dynamically in your system’s environment, so you don’t have to worry about specific Python paths. It’s like giving your script a universal remote to work anywhere.
- Save and Close the File: After adding the shebang line, it’s time to save your work and close the editor. In nano , it’s simple: press Ctrl + X, then hit Y to confirm that you want to save the changes, and hit Enter to exit. Now your script is updated and ready for the next step.
- Make the Script Executable: Now we need to give your script permission to run as an executable. This step is like saying, “Go ahead, you’re free to run.” To do this, use the
chmod
(change mode) command. It’ll mark the script as executable. Here’s the command to run:
chmod +x demo_ai.py
This command adds the “execute” permission to your script, allowing you to run it directly. Once you’ve executed this, your terminal will return to the prompt, and your script is now officially ready to go.
- Run the Script Directly: Now for the best part: running the script! No more typing
python3
every time. Since you’ve made the script executable, you can run it just like any other program. Here’s how:
./demo_ai.py
The ./ part tells the terminal to look for the demo_ai.py script in the current directory. Once you hit enter, it runs the script just like a regular command, and you should see the output right there in the terminal.
By making your Python script executable, you’ve just streamlined your workflow. You can now run your script with a simple command, no need to type python3 every time. This is especially useful when you’re working with multiple scripts or automating tasks, as it cuts down on unnecessary typing and makes everything run smoother. So, go ahead—give it a try! You’ve made your script a lot more efficient and user-friendly.
Make Python Script Executable Guide
How to Handle Both Python 2 and Python 3 Environments
Managing both Python 2 and Python 3 on a single Ubuntu system is a bit like keeping two friends with very different personalities happy in the same room. You don’t want them to clash, and you definitely don’t want their stuff to get mixed up. So, how do you do it? It’s all about setting boundaries—well, not literal ones, but boundaries for your Python environments! For simple scripts, you can just tell your system which version of Python you want to run by explicitly calling the version in your commands. However, if you’re dealing with more complex projects, things get a bit more interesting. The real hero of this story is virtual environments. They allow you to isolate your projects, making sure one version of Python doesn’t trample all over another version or its dependencies.
IMPORTANT NOTE:
Python 2 has been obsolete since 2020, and it’s not getting any updates anymore. If you’re starting new projects, always use Python 3 and its handy `venv` module to create virtual environments. Python 2 should only be used when you’re maintaining old, legacy applications that can’t be upgraded to Python 3.
How to Identify System Interpreters
Before you go around managing Python versions, it’s good to know what you’re working with. Which Python versions are actually installed on your system? You can find out by running a couple of simple commands. Let’s say you want to check for Python 3—you’d run:
$ python3 –version
And if you want to check for Python 2, you can run:
$ python2 –version
If the command for Python 2 gives you a “command not found” error, don’t worry—this just means Python 3 is the only version on your system, and that’s perfectly fine!
How to Explicitly Run Scripts
Alright, so now that you know what’s installed, it’s time to talk about running scripts. Sometimes, you might have both Python 2 and Python 3 installed on your system, and you need to specify which one should run a particular script. You don’t want to let the wrong version of Python hijack your script, right?
To run a script with Python 3, you’d use this command:
$ python3 your_script_name.py
And if you ever need to run it with Python 2, you can do that too:
$ python2 your_script_name.py
By explicitly calling the version you want, you’re in control. You’re like the director of the show, making sure everything runs smoothly.
How to Manage Projects with Virtual Environments (Best Practice)
Here’s where the magic happens: virtual environments. Think of them like private rooms for your projects. Each room has its own set of Python libraries and dependencies, keeping them from interfering with each other. Without these rooms, you’d get a crazy situation known as “dependency hell,” where different projects fight over the same libraries. By using virtual environments, you keep your projects neat, tidy, and conflict-free.
How to Create a Python 3 Environment with venv
Now, how do you actually create one of these isolated environments? The venv module is your friend here. It’s built right into Python 3 and is the easiest way to create a virtual environment for your projects.
First, check if venv is already installed. If it’s not, no worries—just run these commands to install it:
$ sudo apt update
$ sudo apt install python3-venv
Once venv is installed, it’s time to create your virtual environment. Here’s how you do it:
$ python3 -m venv my-project-env
This command creates a new directory called my-project-env, and inside it is everything you need for your isolated Python environment. Now, activate it by running:
$ source my-project-env/bin/activate
Once activated, you’ll notice that your terminal prompt changes to show that you’re now working inside your virtual environment. It’ll look something like this:
(my-project-env) ubuntu@user:~$
From now on, any Python or pip commands you run will use the Python installed in this virtual environment, not the system Python. This means you can safely install all the packages your project needs without worrying about affecting the global Python installation.
How to Create a Python 3 Environment with virtualenv
For older projects that still need Python 2, you can use virtualenv. This package allows you to create isolated environments, not just for Python 3, but for Python 2 as well.
First, install the necessary tools:
$ sudo apt install python3 python3-pip virtualenv
On Ubuntu 20.04+, you might need to enable the universe repository or even download Python 2 from source if it’s not already available.
To create a virtual environment with Python 2, you specify the Python 2 interpreter path:
$ virtualenv -p /usr/bin/python2 my-legacy-env
Then, activate the environment:
$ source my-legacy-env/bin/activate
Now, everything you do in this terminal session will use Python 2 and its own version of pip. Need to install packages for Python 2? You’ve got it! When you’re done and want to return to the global Python setup, just run:
$ deactivate
Understanding Shebang Lines
Now that you’ve got your virtual environments set up, there’s one more thing you might want to do: make your Python scripts executable. This means you don’t have to type python3 every time to run your script. You can make it just like any other executable program.
This is where shebang lines come in. A shebang is the first line of your script and tells the operating system which interpreter to use when running it directly. For Python 3, your shebang line should look like this:
#!/usr/bin/env python3
For Python 2, it would be:
#!/usr/bin/env python2
Once you’ve added the shebang, you need to make the script executable with the chmod command:
$ chmod +x your_script.py
Now, you can run your script directly like this:
$ ./your_script.py
If you want to run your script from anywhere on the system, just move it to a directory in your PATH, like /usr/local/bin. That way, you can call it from any directory without typing the full path.
With all of this in place, you’re now an expert in managing Python versions and virtual environments on Ubuntu. Whether you’re using Python 2 for legacy projects or Python 3 for the future, you’ve got all the tools you need to keep things running smoothly.
How to Identify System Interpreters
Let’s imagine you’re about to build a new Python project on Ubuntu—you know, diving into code and creating something amazing. But, wait a minute! You need to make sure your tools are set up properly. Think of it like preparing your workspace before you start. To avoid confusion and unexpected roadblocks, you need to first check which version of Python is actually installed on your system and make sure it’s the version you want to use. Here’s the thing: your system might have both Python 2 and Python 3 installed, and they can both get a little…well, messy if you don’t know which is which. To make sure everything runs smoothly, you need to check them out first, like checking the labels on your tools before you get started.
To find out which versions of Python are living on your system, just pop open the terminal and run a few commands:
- Check for Python 3: To see if Python 3 is installed (and get the version number), type:
$ python3 –version
This will tell you the version of Python 3 currently chilling on your system. If everything’s good, you’ll see something like this:
Python 3.x.x
- Check for Python 2: Now, what if you need to check for Python 2? Maybe you’re working on some older project or maintaining legacy code. To check if Python 2 is installed, run this command:
$ python2 –version
If Python 2 is on your system, you’ll get an output that looks like this:
Python 2.x.x
But if you get an error saying “command not found,” don’t panic—it simply means Python 2 isn’t installed, or maybe it’s just not in the system path.
So, what’s the big deal with this? Well, once you know which version you’re working with, it’s much easier to make decisions about your scripts and manage the dependencies you’ll need. It’s like knowing which wrench to use before you start fixing your bike. With the right Python version confirmed, you can avoid compatibility issues and keep your projects running like a well-oiled machine!
In short, verifying your Python environment means no surprises down the road—just smooth sailing ahead.
For more details on Python versions, refer to the official documentation.
Python Official Documentation on Versions
How to Explicitly Run Scripts
Let’s say you’re working on a Python project, and you’ve got Python 2 and Python 3 coexisting on your Ubuntu system. Now, things could get tricky if you’re not careful—kind of like trying to drive two cars at once, right? You’ve got to be sure which one you’re hopping into before you hit the road. So, how do you make sure that when you run a script, it’s using the right version of Python? It’s actually pretty simple: you explicitly tell the system which version to use. It’s like saying, “Hey, I want to drive this car today, not that one!” and your system listens. This is especially important when you’re juggling both Python 2 and Python 3, and trust me, you don’t want them to step on each other’s toes.
Running a Script with Python 3
Okay, so Python 3 is where the modern magic happens, and it’s the version you’ll likely be using most of the time. If you’re working on something fresh and shiny (new project, new script), you’ll want to use this version. All you’ve got to do is run:
$ python3 your_script_name.py
This command is like a green light telling your system to pull out the Python 3 interpreter and run your script. Even if you’ve got older versions of Python hanging around, no worries. This command keeps things tidy and ensures that your script runs with the latest and greatest version of Python. If everything’s installed correctly, your script will execute just like you want.
Running a Script with Python 2
Now, here’s the twist. What if you’re dealing with an older project, maybe one built with Python 2? Python 2 might feel like the old, classic car in your garage—it’s not as shiny, but it still gets the job done for certain tasks, especially when it comes to legacy applications. To run a script with Python 2, you’ll have to tell your system to use the old-school version by typing this command:
$ python2 your_script_name.py
This ensures that Python 2 steps in as the interpreter, so you don’t run into issues with code that’s written in a way that Python 3 wouldn’t understand (think of it like trying to use old parts in a new car—it just won’t work unless you’re specific). By making this explicit choice in your terminal, you’re keeping everything in check, ensuring that the right interpreter handles your code. It’s like choosing the right tool for the job, so you avoid confusion and potential errors when bouncing between different versions of Python.
In the end, whether you’re using Python 3 or Python 2, telling your system which one to use gives you the control you need. No more surprises. Just run your script with confidence, knowing you’ve chosen the right version every time. This little step saves you time and keeps your development smooth, no matter which version of Python you’re working with.
For more information, visit the Python documentation for Unix-based systems.
How to Manage Projects with Virtual Environments (Best Practice)
Imagine you’re a developer juggling multiple projects. One project requires Python 3, while another is still rooted in the older days, relying on Python 2. What do you do? Well, here’s the thing: you don’t have to let these two worlds collide. You can create neat little isolated environments where each project can live in peace without messing with the other. This is where virtual environments come into play.
A virtual environment is like a special room for your project. It’s a separate folder that contains its own version of Python and all the libraries it needs, keeping everything contained and tidy. This way, no matter how many different versions of Python you have running on your Ubuntu system, each project can have its own dedicated space with its own dependencies. It’s a life-saver when you’re working on multiple projects at once, each with its own version of Python or a library that’s been updated or changed.
Why Use Virtual Environments?
Now, imagine if you didn’t use virtual environments. You might run into dependency hell—and no, it’s not a term from a science fiction movie. It’s a real issue where two different projects need conflicting versions of the same library, causing chaos in your development process. But if you use virtual environments, each project gets its own version of the library it needs. This means no more annoying clashes, just smooth sailing. You can update one project without worrying about breaking another.
How to Create a Python 3 Environment with venv
The venv module is your best friend when it comes to creating virtual environments in Python 3. It’s built right into Python, so you don’t need any third-party tools. The process is super easy, and it ensures your environment is isolated from your system’s Python installation. Here’s how to get started:
Step-by-Step Guide to Creating a Python 3 Virtual Environment
- Install venv (if needed): First, check if the venv module is installed. If it’s not, no worries. Run these commands to install it:
$ sudo apt update
$ sudo apt install python3-venv
These simple commands will get the venv module on your system.
- Create the Virtual Environment: Now, let’s create the environment. You’ll want to run this command:
$ python3 -m venv my-project-env
In this command, my-project-env is the name of the directory where the virtual environment will live. You can name it anything that makes sense to you.
- Activate the Virtual Environment: After that, we need to activate it. This command switches your terminal into the virtual environment’s mode:
$ source my-project-env/bin/activate
Once activated, your terminal prompt will change. It’ll look something like this:
(my-project-env) ubuntu@user:~$
That means you’re now working in your virtual environment. Any Python commands you run now, like python or pip , will use the environment’s version of Python and its installed packages, not the system’s default.
How to Create a Python 3 Environment with virtualenv
What if you’re working on an old project that still relies on Python 2? Well, you’re not stuck—there’s a tool for that. virtualenv allows you to create environments for both Python 2 and Python 3, so you can manage your legacy projects while keeping everything in check.
Step-by-Step Guide to Creating a Python 2 Virtual Environment with virtualenv
- Install the Prerequisites: Before you can use virtualenv , you’ll need to install it along with the necessary Python versions. Run this command:
$ sudo apt install python3 python3-pip virtualenv
Keep in mind that if you’re using Ubuntu 20.04 or later, Python 2 might not be available by default. You might need to enable the universe repository or install Python 2 from source.
- Create the Virtual Environment with Python 2: Here’s where you specify that you want Python 2 for your environment:
$ virtualenv -p /usr/bin/python2 my-legacy-env
In this case, my-legacy-env is the directory where your Python 2 virtual environment will live. You can name it anything you want, of course.
- Activate the Virtual Environment: Once the environment is created, activate it with:
$ source my-legacy-env/bin/activate
Now, your terminal prompt will change again to indicate you’re in the Python 2 environment. It will look something like this:
(my-legacy-env) ubuntu@user:~$
From here on, any Python or pip commands will use Python 2, so you’re good to go!
- Deactivate the Virtual Environment: When you’re done and want to go back to your default Python, simply run:
$ deactivate
This will take you out of the virtual environment and back to your normal shell.
Understanding Shebang Lines
Now, here’s something really handy. If you want your Python scripts to run directly without always typing python3 or python2 in front, you can use a shebang line. A shebang is the very first line in your script, and it tells the system which interpreter to use. It’s like a personal assistant for your script, guiding it to the right Python interpreter.
For Python 3, your shebang line should look like this:
#!/usr/bin/env python3
For Python 2, you would use:
#!/usr/bin/env python2
Once you’ve added that, don’t forget to make your script executable with this command:
$ chmod +x your_script.py
After that, you can run your Python script directly from the terminal like this:
$ ./your_script.py
And if you want to be able to run your script from any directory on your system (without having to navigate to its folder every time), just move it to a directory that’s part of your system’s PATH, like /usr/local/bin .
Now, with all these steps in place, managing multiple Python versions with virtual environments is a breeze! You’re all set to run your projects independently, and you don’t have to worry about them stepping on each other’s toes. Whether you’re working with Python 3 for your latest projects or Python 2 for legacy apps, you’ve got the tools to handle it.
Remember to always use virtual environments to avoid dependency issues across projects.
Virtual Environments in Python Documentation
How to Create a Python 3 Environment with venv
Let’s imagine you’re knee-deep in a couple of Python projects, each with its own set of dependencies. One project is running smoothly with the latest libraries, but another one is stuck in the past, needing older versions of some packages. What do you do? You certainly don’t want these two projects to step on each other’s toes, right? That’s where venv comes in. The venv module is like a superhero for Python developers. It’s built right into Python 3 and allows you to create isolated environments for your projects. By creating a separate environment for each project, you keep all your dependencies in one neat little bubble, preventing those nasty dependency hell issues. Each project gets its own version of Python and its specific libraries, so nothing breaks when you switch between them. Sounds like magic, doesn’t it?
Steps to Create a Python 3 Virtual Environment with venv
Let’s break it down step by step so you can get your hands dirty and set up a virtual environment for your project.
- Install venv (if not already installed): First things first—check if the venv module is already installed on your Ubuntu system. If not, no worries. You can easily install it by running these commands in your terminal:
$ sudo apt update
$ sudo apt install python3-venv
These commands will update your package list and then install the python3-venv package. That’s the key to creating your isolated environment.
Create the Virtual Environment: Now, let’s move on to the fun part. You’re going to create the actual virtual environment. Run the following command:
$ python3 -m venv my-project-env
In this case, my-project-env is the name of the folder where the virtual environment will live. You can name it something that fits your project better—maybe something like data-science-env or flask-webapp-env . This command will create a folder, and inside it, you’ll find a fresh Python environment, complete with its own version of Python and pip (the package manager). Everything will be contained within that folder, keeping it nice and tidy.
Activate the Virtual Environment: Once the environment is created, you need to activate it. Activating the environment is like flipping a switch to tell your terminal, “Hey, I want to use this environment now, not the global system one.” To activate it, run this command:
$ source my-project-env/bin/activate
After activation, something cool happens: your terminal prompt changes to show the name of the virtual environment. It’ll look something like this:
(my-project-env) ubuntu@user:~$
That little (my-project-env) at the start of the prompt is your signal that you’re now working within the virtual environment you just created.
Use the Virtual Environment: Now that the environment is activated, any python or pip commands you run in the terminal will refer to the version inside the virtual environment, not your system’s global Python setup. This is key because it allows you to install libraries and manage your project’s dependencies without messing with other projects or system-wide packages. Want to install a package? Use pip install just like you always do, but now it’ll only affect this project.
And there you have it! With just a few simple steps, you’ve created an isolated environment for your Python project. You’ve ensured that your dependencies are well-managed and safe from conflicts, which means you can focus on your code, not on package headaches. It’s a best practice in Python development that will make your life so much easier in the long run.
Now, go ahead, create as many environments as you like for different projects—whether it’s Python 3, Flask, or Django—without ever having to worry about breaking something in another project. Enjoy coding without the fear of package conflicts, knowing your projects are safe and sound in their own little bubbles.
Python virtual environments are a great way to ensure that each project’s dependencies are isolated and won’t interfere with one another.
Python Virtual Environments: A Primer
How to Create a Python 3 Environment with virtualenv
Picture this: you’re working on a legacy project that still requires Python 2, but your system is running Python 3. The thought of juggling different Python versions on the same system might sound a little intimidating, right? But don’t worry, there’s a way to handle this situation smoothly—and that’s where the virtualenv package comes in.
This clever tool lets you create isolated environments on your system, meaning you can run your older Python 2 projects without messing with your default Python 3 setup. It’s perfect for legacy applications that haven’t made the leap to Python 3 yet. Now, let’s break down how to make this magic happen!
Steps to Create a Python 2 Virtual Environment with virtualenv
- Install the Prerequisites:
Before you get started, you’ll need to make sure your system has all the right tools. You’ll need Python 3, pip (which is Python’s package manager), and the virtualenv package. Don’t worry, installing these is a breeze. Just run the following commands in your terminal:
$ sudo apt install python3 python3-pip virtualenv
This installs the latest Python 3, pip, and the virtualenv package for creating isolated environments. Now, here’s the catch—if you’re using Ubuntu 20.04 or later, Python 2 might not be installed by default. In that case, you might need to enable the universe repository or manually download Python 2 if it’s not available via apt. Don’t fret though, it’s just one small step.
- Create a Python 2 Virtual Environment:
Now for the fun part: creating the virtual environment itself. To set up an environment that specifically uses Python 2, you’ll need to specify the path to the Python 2 interpreter. Here’s the command:
$ virtualenv -p /usr/bin/python2 my-legacy-env
So, what’s going on here? Let’s break it down:
- -p /usr/bin/python2 tells virtualenv to use Python 2.
- my-legacy-env is the name of your new environment’s folder. You can name it whatever you want—maybe something like python2-legacy-project, depending on what makes sense for your project.
After you run this command, a brand new directory will appear—containing a clean Python 2 environment, completely separated from your global Python installation.
- Activate the Virtual Environment:
Now that your virtual environment is ready, you need to activate it. Activating it is like putting on a special hat. Once it’s on, you know you’re in the right space for your project. To activate the virtual environment, just run:
$ source my-legacy-env/bin/activate
After this command, your terminal prompt will change to reflect that you’re working within the virtual environment. For example, you’ll see something like:
Output(my-legacy-env) ubuntu@user:~$
That (my-legacy-env) prefix means you’re now working inside the environment, and everything you do with Python and pip will be isolated to that specific environment.
- Working Within the Virtual Environment:
While you’re in your newly activated virtual environment, the Python and pip commands will be locked into the Python 2 environment you just created. This is a great way to install dependencies specific to your legacy project without affecting your global Python setup.
For example, let’s say you need to install a Python 2-specific package. You can easily do this by running:
$ pip install some-package
This package will only be installed within the virtual environment, so your system’s default Python installation remains untouched. Pretty neat, right?
- Deactivate the Virtual Environment:
Once you’re done working in the virtual environment, you can deactivate it and return to the default system Python environment. To do this, simply type:
$ deactivate
This will return your terminal session to the global Python environment, where Python and pip will once again use the system’s default Python version.
By following these simple steps, you can create and manage Python 2 environments for your legacy projects without breaking a sweat. This approach ensures that your development work remains compatible with older Python versions while still enjoying the benefits of isolated environments for each project. It’s a smart way to keep your projects neat and conflict-free!
Remember, creating virtual environments keeps your legacy projects from interfering with your system’s default Python setup.
Understanding Shebang Lines
Let’s take a moment to talk about a little magic trick that makes running your Python scripts easier than ever: the shebang line. It’s that first line in your Python script that quietly works behind the scenes to tell the system, “Hey, this is how you should run me.” Without it, you’d have to explicitly type python every time you want to run your script—like having to specify every detail of a recipe instead of just using a shortcut. But with the shebang in place, your script is ready to run, just like any other program you have on your system.
Shebang Syntax for Python
Alright, let’s dive into the technical bit. For Python 3, your shebang line should look like this:
#!/usr/bin/env python3
This line is doing some heavy lifting. It tells your system, “I want you to use Python 3 to execute this script.” But here’s the cool part: the env command ensures that Python 3 gets found automatically, regardless of where it’s installed on your system. No more worrying if Python 3 is buried in some random directory on your machine—it’ll always work.
Now, if you’re still working with Python 2 (maybe a legacy project or an old script you can’t quite retire), the shebang will be a bit different:
#!/usr/bin/env python2
This one does the same job as the Python 3 shebang but for Python 2, telling your system to use the Python 2 interpreter for execution. If you’re running older scripts that still rely on Python 2-specific features, this shebang line is your best friend.
Making the Script Executable
Now, the shebang line is like your script’s passport, telling the system where to go to run it. But before your script can board the execution flight, you need to make sure it has permission to take off! That’s where the chmod (change mode) command comes into play. It’s like giving your script a VIP pass to be run directly from the terminal.
To do this, just run:
chmod +x your_script.py
This little command grants the script the necessary permissions to be executed. After this, you won’t need to type python every time. You can just fire up your script like a real program, straight from the terminal.
Running the Script
Now, it’s showtime. With your script made executable, you can run it directly from the terminal. Just navigate to the folder where your script lives, and use this command:
./your_script.py
What happens here is pretty simple: the terminal knows to look for the script in the current directory (that’s what the ./ does). It uses the shebang to figure out which interpreter to run, so everything works seamlessly, just like running any other command or program.
Running the Script Globally
Here’s a little bonus trick: what if you don’t want to have to remember which folder your script is in? Maybe you’re using a script you want to run from anywhere on your system, no matter where you are in the terminal. Well, there’s a solution for that, too.
If you move your script to a directory in your system’s PATH (like /usr/local/bin ), you can run your script from anywhere, without worrying about its location. The PATH is a list of directories that the system checks whenever you run a command in the terminal, so if your script is in there, the system will find it no matter where you are.
To do this, you can use the following command:
sudo mv your_script.py /usr/local/bin/
Once the script is in one of the PATH directories, you can run it from any terminal window by simply typing:
your_script.py
This is especially handy if you’ve got a bunch of utility scripts you want to access easily, no matter where you are in your terminal.
By using shebang lines and making scripts executable, you’re streamlining your Python workflow. You’ve taken a few simple steps to make running scripts more efficient, eliminating the need for repetitive commands. It’s a small change, but it can really speed up your development process.
Troubleshooting: Common Errors and Solutions
Working with code can sometimes feel like being a detective. Errors pop up like little roadblocks, but each one is just a clue leading you toward the solution. While this might seem frustrating at first, once you get the hang of it, you’ll realize that each error is just part of the process. These issues usually revolve around permissions, file paths, or the Python installation itself, so let’s break down some common errors you’ll encounter and how to solve them.
1. Permission Denied
Error Message:
$ bash: ./your_script.py: Permission denied
The Cause:
So, you’ve written a beautiful Python script, and you’re ready to run it, but—boom!—the terminal stops you in your tracks with a “Permission denied” error. What gives? Well, what’s happening here is that you’re trying to execute the script directly, but your system hasn’t been told that it’s okay for this file to be run. The operating system has blocked it for security reasons to keep things safe.
The Solution:
No need to panic—this is a quick fix! You just need to grant execute permissions to your script. Use the chmod command, which is like telling your system, “Yes, this script is trustworthy.” Here’s how to do it:
$ chmod +x your_script.py
Once that’s done, you should be able to run the script as planned:
$ ./your_script.py
Boom! Your script is now ready to run directly from the terminal.
2. Command Not Found
Error Message:
$ bash: python: command not found or bash: python3: command not found
The Cause:
You might run into this error if the terminal can’t find the Python interpreter. This usually means that either Python isn’t installed on your system or it’s not in your system’s PATH—basically, the list of places the terminal looks when you type a command.
The Solution:
No sweat. First, you’ll want to make sure Python is installed. Since Python 3 is the way to go for modern development, here’s what you do:
$ sudo apt update
$ sudo apt install python3
If you like the python command, and want it to point to Python 3 (because, let’s be honest, who wants to type python3 every time?), you can do that too:
$ sudo apt install python-is-python3
This will set python to always use Python 3, so you can run your scripts without the extra digits. Now, you can get back to coding with the familiar python command!
3. No Such File or Directory
Error Message:
$ python3: can’t open file ‘your_script.py’: [Errno 2] No such file or directory
The Cause:
Uh-oh! You’ve typed out the command to run your script, but the terminal can’t find it. This usually happens if either the file doesn’t exist in the directory you’re in, or maybe you’ve typed the filename wrong (oops!).
The Solution:
First, let’s double-check that you’re in the right place. Run:
$ pwd
This will show you the directory you’re currently in. Next, let’s make sure the script is actually there. Type:
$ ls
This will list all the files in your current directory. Scan through and make sure the name of the script is exactly what you typed—don’t forget that filenames can be case-sensitive!
If you’re not in the right directory, use:
$ cd ~/scripts
to change to the folder where your script is located. Once you’re in the right place, you can run your script like this:
$ python3 your_script.py
And just like that, your script will execute as expected!
So there you have it. Errors are a natural part of coding, but once you understand the cause of each one, you can fix them in no time. Whether it’s a permission issue, a missing Python installation, or a simple file path mistake, tackling these challenges head-on will help you build confidence and keep your development workflow smooth. Just remember, every error message is a little puzzle waiting to be solved!
Conclusion
In conclusion, running Python scripts on Ubuntu is a crucial skill for developers looking to streamline their workflows. By mastering Python environments, especially virtual environments, you can effectively manage dependencies and avoid common issues like compatibility conflicts. Whether you’re working with Python 2 or Python 3, this guide has equipped you with the necessary steps to set up, create, and execute Python scripts with ease. Virtual environments offer a clean and organized way to keep projects isolated and dependencies in check, ensuring smoother development processes. Moving forward, as Python continues to evolve, understanding and leveraging these techniques will only become more important, especially as tools like Docker and virtual environments gain even more significance in modern development practices.Snippet: Master running Python scripts on Ubuntu by using virtual environments to manage dependencies and execute code seamlessly.
Master Python Modules: Install, Import, and Manage Packages and Libraries
Manage Users
October 6, 2025[…] Run Python Scripts on Ubuntu: Master Virtual Environments and Execution (2025) […]
Run Python Scripts on Ubuntu: Setup, Execution, and Best Practices
October 6, 2025[…] Run Python Scripts on Ubuntu: Master Virtual Environments and Execution […]