CARVIEW |
- Log in to:
- Community
- DigitalOcean
- Sign up for:
- Community
- DigitalOcean
By Easha Abid and Manikandan Kurup

Introduction
Running a Python script on Ubuntu is a fundamental skill for developers, system administrators, and data scientists. Whether you’re automating tasks, running a web server, or training a machine learning model, understanding the proper execution methods is essential. This article provides a comprehensive overview of how to run Python scripts on Ubuntu, covering everything from basic commands to professional best practices.
In this article, we walk you through setting up a proper Python environment and creating your first script. You’ll learn the primary methods for execution, including using the python3
command directly and making your scripts executable with a shebang line. We also cover how to manage different project requirements using virtual environments, handle systems with both Python 2 and 3, and troubleshoot common errors.
Key Takeaways
- The most direct way to run a Python script on Ubuntu is by using the
python3 your_script.py
command in your terminal. - Always use a virtual environment (
venv
) to isolate project dependencies and avoid conflicts with the system’s Python packages. - You can make a script run like a native command by adding a
#!/usr/bin/env python3
shebang line and making the file executable withchmod +x
. - Required third-party libraries for your script must be installed into your active virtual environment using
pip install
. - For clarity and compatibility, explicitly use the
python3
command, as Python 2 is obsolete and not installed on modern Ubuntu systems. - Common errors like
"Permission denied"
or"ModuleNotFoundError"
can be quickly fixed by setting execute permissions or installing packages into the correct environment.
Prerequisites
To follow this tutorial, you will need:
-
A server running Ubuntu along with a non-root user with sudo privileges and an active firewall. For guidance on how to set this up, refer to our initial server setup with Ubuntu guide. Please ensure you are working with a supported version of Ubuntu.
-
Familiarity with the Linux command line. For an introduction or refresher to the command line, you can visit this guide on Linux command line primer.
-
Before starting, run
sudo apt-get update
in the Ubuntu terminal to ensure your system has the latest versions and security updates for the software available from the repositories configured on your system.
These instructions are valid for the most recent versions of Ubuntu: Ubuntu 24.04, Ubuntu 22.04, and Ubuntu 20.04. If you are using Ubuntu version <= 18.04, we recommend you upgrade to a more latest version since Ubuntu no longer provides support for these versions. This collection of guides will help you in upgrading your Ubuntu version.
Run Python Script on Ubuntu
To run a Python script on Ubuntu, we’ll follow these steps:
- Setup Python Environment
- Create Python Script
- Install Required Packages
- Run Python Script
- Make the Script Executable
Step 1 - How to Setup Python Environment
Ubuntu 24.04 ships Python 3 by default. Open the terminal and run the following command to double-check Python 3 installation:
python3 --version
If Python 3 is already installed on your machine, this command will return the current version of Python 3 installation. In case it is not installed, you can run the following command and get the Python 3 installation:
sudo apt install python3
Next, you need to install the pip
package installer on your system:
sudo apt install python3-pip
Step 2 - How to Create Python Script
The next step is to write the Python code you want to execute. To create a new script, navigate to your directory of choice:
cd ~/path-to-your-script-directory
When inside the directory, you need to create a new file. In the terminal, execute the following command:
nano demo_ai.py
This will open up a blank text editor. Write your logic here or copy the following code:
from sklearn.tree import DecisionTreeClassifier
import numpy as np
import random
# Generate sample data
x = np.array([[i] for i in range(1, 21)]) # Numbers 1 to 20
y = np.array([i % 2 for i in range(1, 21)]) # 0 for even, 1 for odd
# Create and train the model
model = DecisionTreeClassifier()
model.fit(x, y)
# Function to predict if a number is odd or even
def predict_odd_even(number):
prediction = model.predict([[number]])
return "Odd" if prediction[0] == 1 else "Even"
if __name__ == "__main__":
num = random.randint(0, 20)
result = predict_odd_even(num)
print(f"The number {num} is an {result} number.")
This script creates a simple decision tree classifier using the scikit-learn
library. It trains the model to recognize odd and even numbers based on the randomly generated sample data. It then makes a prediction based on its learning for the given number.
Save and exit the text editor.
Step 3 - How to Install Required Packages
In this step, you will install the packages you have used in the script above.
The first package you need to install is NumPy. You used this library to create a dataset for training the machine learning model.
Starting from Python 3.11 and pip 22.3, there’s a new PEP 668 that states the marking of Python base environments as “externally managed”. Which is why simply running pip3 scikit-learn numpy
or similar numpy installation commands will throw error: externally-managed-environment
.
To install and use numpy
successfully, you need to create a virtual environment that isolates your Python packages from the system environment. This is important because it keeps dependencies required by different projects separate and avoids potential conflicts between package versions.
First, install virtualenv
by running:
sudo apt install python3-venv
Now, use this tool to create a virtual environment inside your working directory.
python3 -m venv python-env
The next step is to activate this virtual environment by executing the activate script.
source python-env/bin/activate
On execution, you will notice the terminal prompt prefixed with your virtual environment name like this:
Output(python-env) ubuntu@user:
Now, install the required packages by running:
pip install scikit-learn numpy
The random
module is part of Python’s standard library, so you do not need to install it separately. It is included with Python and can be used directly without any additional installations.
Step 4 - How to Run Python Script
Now that you have all the required packages in place, you can run your Python script by executing the following command inside your working directory:
python3 demo_ai.py
Upon successful execution, you will see the desired output.
Output(python-env) ubuntu@user:~/scripts/python demo_ai.py
The number 5 is an Odd number.
(python-env) ubuntu@user:~/scripts/python demo_ai.py
The number 17 is an Odd number.
Step 5 - How to Make the Script Executable [OPTIONAL]
Making the script executable allows you to run it directly without needing to explicitly call Python by typing python3
. This makes running your script quicker and more convenient.
Open your Python script using a text editor.
nano demo_ai.py
On top of the file, add a shebang i.e. #!
line that tells the system what interpreter to use when executing the script. Add the following line as the first line of your script:
#!/usr/bin/env python3
Save and close the file.
Now, make this script executable to allow it to run like any other program or command in your terminal.
chmod +x demo_ai.py
On successful execution, you will see the control returned to you immediately. Starting now, you can simply run your script as follows:
./demo_ai.py
How to Handle both Python 2 and Python 3 environments
To effectively manage Python 2 and Python 3 on a single Ubuntu system, you should use explicit commands for simple scripts and dedicated virtual environments for projects. This approach prevents version and dependency conflicts.
IMPORTANT NOTE Python 2 is obsolete and has been unsupported since 2020. It receives no security updates. Always use Python 3 and venv for new projects. Only use Python 2 environments for maintaining legacy applications that cannot be upgraded.
How to Identify System Interpreters
First, check which Python versions your system has installed and where the default python
command points.
Run these commands to see what’s available:
# Check for Python 3
python3 --version
# Check for Python 2
python2 --version
If the python2
command returns a "command not found"
error, it means only Python 3 is installed.
How to Explicitly Running Scripts
The simplest way to control which version runs your script is to call it explicitly.
-
To run a script with Python 3:
python3 your_script_name.py
-
To run a script with Python 2:
python2 your_script_name.py
How to Manage Projects with Virtual Environments (Best Practice)
A virtual environment is an isolated folder containing a specific Python version and its own libraries. This is the professional standard as it prevents “dependency hell,” where different projects need conflicting versions of the same package.
How to Create a Python 3 Environment with venv
The venv
module is built into Python 3 and is the standard for creating virtual environments.
-
First, install
venv
(if needed):sudo apt update sudo apt install python3-venv
-
Then, create and activate the virtual environment:
# Create the environment folder python3 -m venv my-project-env # Activate it source my-project-env/bin/activate
After activation, your prompt will change, and the python
and pip
commands inside this terminal session will automatically use the Python 3 interpreter and its package installer.
How to Create a Python 3 Environment with virtualenv
For legacy projects, you’ll need the virtualenv
package.
- First install the prerequisites:
sudo apt install python3 python3-pip virtualenv
Note: On Ubuntu 20.04+ you may need to enable the universe repository or download Python 2 from source if not available via apt
.
- Then create and activate
virtualenv
:
# Create the environment, specifying the Python 2 interpreter path
virtualenv -p /usr/bin/python2 my-legacy-env
# Activate it
source my-legacy-env/bin/activate
Once activated, the python
and pip
commands will now point to the system’s Python 2.
To leave any environment and return to your normal shell, simply run deactivate
.
Understanding Shebang Lines
A shebang is the first line in a script that tells the OS which interpreter to use when the script is run directly as an executable.
- For Python 3:
#!/usr/bin/env python3
- For Python 2:
#!/usr/bin/env python2
For this to work, you must make the script executable:
chmod +x your_script.py
Then you can run it directly, and the system will respect the shebang:
./your_script.py
And if you want to run your script globally (from any directory), move it to a directory in your PATH
like /usr/local/bin
.
Troubleshooting: Common Errors and Solutions
Encountering an error is a normal part of the development process. Think of it as your computer giving you a specific clue to solve a puzzle. Here are some of the most frequent errors you might see in the terminal and how to fix them. They are usually related to permissions, file paths, or the Python installation itself.
1. Permission Denied
bash: ./your_script.py: Permission denied
The Cause: You’re trying to run a script directly (./your_script.py
), but the file doesn’t have the “execute” permission. The operating system is stopping you for security reasons.
The Solution: Use the chmod
(change mode) command to add the execute permission.
chmod +x your_script.py
Now you can run it again with ./your_script.py
.
2. Command Not Found
bash: python: command not found
Or:
bash: python3: command not found
The Cause: Ubuntu can’t find the python
or python3
interpreter. This means Python either isn’t installed, or it’s not in the system’s PATH
(a list of directories where the shell looks for commands).
The Solution: Install Python 3. This is the standard for all modern development.
sudo apt update
sudo apt install python3
For convenience, you can also install a package that makes the python
command point to python3
:
sudo apt install python-is-python3
3. No Such File or Directory
python3: can't open file 'your_script.py': [Errno 2] No such file or directory
The Cause: You’re trying to run a script that doesn’t exist in your current directory, or you’ve made a typo in the filename.
The Solution:
- First, confirm you’re in the right directory using pwd (print working directory).
- Next, list the files in your current directory with ls to check the exact spelling of your script.
- If you’re in the wrong place, use the cd command to navigate to the correct directory.
Frequently Asked Questions (FAQs)
1. How do I run a .py file in Ubuntu?
The most straightforward way to run a Python file in the Ubuntu terminal is by using the python3
command. To do this:
-
Open your terminal and navigate to the directory containing your file using the
cd
command. -
Run the script by typing:
python3 your_script_name.py
2. Why do I get “Permission denied” when running a script?
You get a “Permission denied” error when you try to run the script as a direct executable (e.g., ./your_script.py
), but the file doesn’t have the necessary “execute” permission.
To resolve this, use the chmod
command to add the execute permission to your file.
chmod +x your_script_name.py
After running this command, you will be able to run the script using ./your_script_name.py
.
3. Do I need to install Python on Ubuntu?
Probably not. Modern versions of Ubuntu (20.04 and newer) come with Python 3 pre-installed because many core system tools depend on it.
You can verify this by opening a terminal and typing python3 --version
. You only need to install it manually if you are using a very old version of Ubuntu or if it has been explicitly removed.
4. What’s the difference between running python script.py
and python3 script.py
on Ubuntu?
python
might point to Python 2.x (if installed) or may not exist at all on newer Ubuntu versions. python3
explicitly runs Python 3.x. It’s recommended to use python3
for clarity and compatibility, especially since Python 2 is deprecated.
Conclusion
In this article, you’ve learned how to successfully execute Python scripts on an Ubuntu system. We walked through everything from the basic python3 script.py
command to making your scripts directly executable with a shebang and chmod
. You also learned how to manage project dependencies professionally using virtual environments, handle systems with multiple Python versions, and troubleshoot common errors you might encounter. With these skills, you are now well-equipped to execute Python code effectively for any project, from simple automation to complex applications.
Now that you know how to execute Python scripts on Ubuntu, let’s put these skills to test by building some practical applications:
- How To Build a Slackbot in Python on Ubuntu 20.04 - Learn how to create an automated bot for Slack that can respond to messages, handle commands, and integrate with your workspace’s workflows
- How To Build a Discord Bot in Python on Ubuntu 20.04 - Create a custom Discord bot that can moderate channels, respond to user commands, and add fun interactive features to your server
- How To Build a Data Processing Pipeline Using Luigi in Python on Ubuntu 20.04 - Build a robust data pipeline that can handle complex workflows, dependencies, and large-scale data processing tasks using the Luigi framework
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
About the author(s)
With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.
Still looking for an answer?
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
- Table of contents
- Key Takeaways
- Prerequisites
- Run Python Script on Ubuntu
- How to Handle both Python 2 and Python 3 environments
- Troubleshooting: Common Errors and Solutions
- Frequently Asked Questions (FAQs)
- Conclusion
Deploy on DigitalOcean
Click below to sign up for DigitalOcean's virtual machines, Databases, and AIML products.
Become a contributor for community
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
DigitalOcean Documentation
Full documentation for every DigitalOcean product.
Resources for startups and SMBs
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Get our newsletter
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
The developer cloud
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Get started for free
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.