How To Run Python In Linux

How To Run Python In Linux

Reading time1 min
#Python#Linux#Programming#pyenv#venv#Docker

Mastering Python Execution on Linux: From Terminal Basics to Advanced Environment Management

Linux is the backbone of countless servers and development environments; mastering Python on this platform empowers developers to deploy, test, and scale applications with precision and efficiency.

Forget installing Python and running scripts the easy way—unlock the power of environment modules, version managers, and containerized Python setups to streamline your Linux workflow, and avoid common pitfalls that slow down productivity.


Introduction

Python on Linux isn’t just about running a simple script by typing python script.py. Whether you’re a beginner or seasoned dev, understanding how Python interacts with your Linux environment is crucial to writing efficient, maintainable code and managing projects that require different dependencies or Python versions.

This guide takes you from the basics of running Python in the terminal to advanced Python environment management techniques that keep your work lean, reproducible, and conflict-free.


1. Running Python Scripts in Linux Terminal: The Basics

First things first—for any kind of mastery you need a solid foundation.

Checking If Python Is Installed

Open your terminal and run:

python3 --version

If you see something like:

Python 3.8.10

You have Python installed! If not, install it using your package manager:

  • Ubuntu/Debian:

    sudo apt update
    sudo apt install python3 python3-pip
    
  • Fedora:

    sudo dnf install python3 python3-pip
    

Running a Simple Script

Create a file called hello.py:

print("Hello from Linux!")

Run it with:

python3 hello.py

Using the Interactive Interpreter

You can launch a quick interpreter by typing:

python3

Then write any quick commands before exiting with exit() or Ctrl+D.


2. Managing Multiple Python Versions: Pyenv to the Rescue

Often, your projects require different versions of Python. Installing all these manually can get messy.

Enter pyenv, an awesome version manager that isolates installed Pythons per user.

Installing pyenv

On Ubuntu/Debian:

curl https://pyenv.run | bash

Add these lines to your .bashrc or .zshrc:

export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv virtualenv-init -)"

Restart terminal or source config file.

Installing Multiple Versions

List available versions:

pyenv install --list | grep " 3\."

Install a specific version:

pyenv install 3.9.13
pyenv install 3.10.4

Set global default (used when no local override applies):

pyenv global 3.10.4
python --version   # Should show Python 3.10.4 now.

Set project-specific version (local override):

cd ~/myproject/
pyenv local 3.9.13    # Creates .python-version file here.
python --version      # Shows 3.9.13 while in this directory.

Why Pyenv?

  • Avoid conflicts between system Python and project Pythons.
  • Easily switch between versions without sudo calls.
  • Test compatibility easily on multiple versions.

3. Virtual Environments: Isolating Your Project Dependencies

Beyond just different interpreters, each project tends to have unique dependencies.

Using virtual environments keeps dependencies sandboxed so they don’t clash across projects.

Create Virtual Environment (venv)

Python comes with built-in support for virtual environments.

Inside your project directory:

python3 -m venv venv   # Create env named venv inside project folder.
source venv/bin/activate    # Activate environment.
pip install requests     # Example dependency.
deactivate              # Exit environment when done.

Verify inside env with:

which python    # Should point inside your project’s 'venv' folder.
pip list        # Will show only project-specific packages.

TIP: Use .gitignore to ignore venv/ folder from Git commits.


4. Advanced Environment Management: Poetry & Pipx

Some prefer comprehensive tools like Poetry for dependency and packaging management beyond pip.

Poetry Basics

Install Poetry globally using pipx (comes later):

curl -sSL https://install.python-poetry.org | python3 -
poetry --version

Create & manage projects easily with lock files ensuring reproducible installs:

poetry new myproject       # Scaffold new project.
cd myproject

poetry add flask           # Install Flask within poetry-managed venv.
poetry run python app.py   # Run commands inside poetry shell.
poetry shell               # Activate shell environment explicitly.
poetry lock                # Generate lock file tracking deps exactly.

Poetry streamlines env creation + packaging workflows for production-ready apps.


5. Containerizing Your Python Apps for Consistent Linux Deployment (Docker)

When sharing or deploying apps across machines or servers, Docker containers eliminate "works on my machine" drama by bundling code+dependencies+environment in isolated images.

Minimal Dockerfile Example for Python App

Create this within your project folder (Dockerfile):

# Use latest official lightweight python base image.
FROM python:3.10-slim

# Set working dir inside container.
WORKDIR /app

# Copy requirements + app files into container.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

# Run your script by default (replace as needed).
CMD ["python", "app.py"]

Build image:

docker build -t my-python-app .

Run container interactively:

docker run --rm -it my-python-app

This method isolates not only dependencies but also the OS-level environment — invaluable for production servers where consistency matters most.


Summary Checklist: Steps to Master Python Execution on Linux

  • ✅ Verify/install the right system-wide Python version (python3 --version).
  • ✅ Use pyenv to switch/manage multiple interpreters per project need.
  • ✅ Always create isolated virtual environments (venv) per project to avoid conflicts.
  • ✅ Use advanced managers like Poetry for dependency/version resolution in more complex projects.
  • ✅ Containerize apps using Docker for consistent cross-machine deployments.

Final Tips & Tricks

  • Avoid installing packages globally with sudo pip; it upsets system package managers!
  • Automate activating virtual environments by adding autoenv or direnv tools if desired.
  • When running scripts directly (./script.py), start with shebang line #!/usr/bin/env python3 and make file executable (chmod +x script.py).
  • Keep an eye on performance differences especially if mixing system-installed Python and other sources like Anaconda or Homebrew on WSL/Linux variants.

Mastering how you execute—and isolate—Python code on Linux is essential in our modern dev ecosystems where multiple projects share a machine, or servers require rock-solid reliability at runtime.

Go forth, experiment, build elegant scripts and scalable apps—and let Linux be your powerful staging arena!

Happy coding!


If you found this guide useful, consider subscribing for more deep dives into dev workflows & tips.