Running Python Scripts on Ubuntu Linux: Practical Methods and Examples
Preparing and Running a Python Script on Ubuntu
We'll start with a basic Python script named greet_user.py that reads a name from enput and outputs a personalized greeting:
def get_formatted_greeting(name):
return f"Greetings, {name}! Welcome to Ubuntu Python scripting."
if __name__ == "__main__":
user_name = input("Enter your name: ")
print(get_formatted_greeting(user_name.strip()))
Core Execution Approaches
1. Direct Terminal Invocation
First validate Python installation with these version checks:
# Python 3 check (default for modern Ubuntu)
python3 --version
# Optional: Check for legacy Python 2
python --version
If Python 3 isn't present, install it via APT:
sudo apt update && sudo apt install python3 python3-pip -y
Run the script with the Python 3 interpreter directly:
python3 greet_user.py
2. Self-Executable Script with Shebang
Modify greet_user.py to start with a shebang line pointing to the system Python 3 executable. Use env for portability across different environments:
#!/usr/bin/env python3
def get_formatted_greeting(name):
return f"Greetings, {name}! Welcome to Ubuntu Python scripting."
if __name__ == "__main__":
user_name = input("Enter your name: ")
print(get_formatted_greeting(user_name.strip()))
Grant execute permissions and run the script without explicitly calling the enterpreter:
chmod 755 greet_user.py
./greet_user.py
3. Isolated Execution with a Python Virtual Environment
Install the venv module (included by default with Python 3.3+; install explicitly if missing):
sudo apt install python3-venv -y
Create and activate a dedicated virtual environment named py_workspace:
# Create environment directory
python3 -m venv py_workspace
# Activate on Bash/Zsh
source py_workspace/bin/activate
# Activate on Fish shell
# source py_workspace/bin/activate.fish
With the environment active, install any dependencies (if needed) and execute the script. The python command will now map to the virtual environment's Python 3 binary:
python greet_user.py
To exit the virtual environment, use:
deactivate