To run a python script on ubuntu is easy, follow this post to know and understand about the python script.
Python is a high-level, interpreted programming language known for its simplicity, readability, and versatility. It was created by Guido van Rossum and first released in 1991. Python is widely used in various fields such as web development, data analysis, artificial intelligence, automation, and more.
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, please choose your distribution from this list and follow our initial server setup guide. Please ensure to work 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.
Step 1 – Python Environment Setup
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 – 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 – 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.
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
Step 4 – 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
Step 5 – Make the Script Executable
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. Append the following line before your code:
#!/usr/bin/env python3
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
Conclusion
Running Python scripts on an Ubuntu machine is a straightforward process. By understanding how to run Python scripts, you can begin exploring the powerful tools Python offers, including those essential for AI development.