Backend & Languages

Python Setup & Deployment Guide

Install Python, manage packages with venv and pip, write a script or small service, and run it reliably on a Linux server.

Updated Official documentation ↗

1. Introduction & use cases

Python is a general-purpose programming language known for readable syntax and a huge ecosystem. It powers web back-ends (Django, Flask, FastAPI), data science (pandas, NumPy), machine learning (PyTorch, scikit-learn), automation scripts and DevOps tools.

Packages come from PyPI via pip. Always work inside a virtual environment so each project has its own package versions, and list them in requirements.txt (or pyproject.toml).

Where it is used

  • Web APIs and websites
  • Data analysis, reports and machine learning
  • Automation: file processing, scraping, scheduled jobs
  • Scripting cloud infrastructure (boto3 for AWS)

2. Prerequisites

You needVersion / notes
PythonA supported 3.x release (3.11 or newer recommended) – check with python3 --version
pip + venvIncluded with Python (on Ubuntu install python3-venv)
EditorVS Code with the Python extension, or PyCharm
TerminalPowerShell / Terminal / bash

3. Local setup

  1. 1Install Python

    Windows: download from python.org and tick “Add python.exe to PATH”. macOS: python.org installer or brew install python. Linux: use the system package.

    BASH
    # Ubuntu / Debian
    sudo apt install -y python3 python3-venv python3-pip
    
    # check (Windows: py --version)
    python3 --version
  2. 2Create a project folder

    Keep code, venv and requirements together.

    BASH
    mkdir py-demo && cd py-demo
  3. 3Create and activate a virtual environment

    A venv keeps each project’s packages separate. Activate it in every new terminal.

    BASH
    python3 -m venv .venv
    
    # macOS / Linux
    source .venv/bin/activate
    # Windows (PowerShell)
    .venv\Scripts\Activate.ps1
    
    python -m pip install --upgrade pip
  4. 4Install packages and record them

    Install what you need, then freeze exact versions.

    BASH
    pip install requests python-dotenv
    pip freeze > requirements.txt

4. Create & run a project

  1. 1Write a script

    This script reads an API URL from .env, fetches JSON and prints a summary. if __name__ == "__main__" lets you import functions without running the script.

    main.py
    import os
    import requests
    from dotenv import load_dotenv
    
    load_dotenv()
    API_URL = os.getenv("API_URL", "https://jsonplaceholder.typicode.com/todos")
    
    def summary() -> str:
        todos = requests.get(API_URL, timeout=10).json()
        done = sum(1 for t in todos if t["completed"])
        return f"{done} of {len(todos)} tasks completed"
    
    if __name__ == "__main__":
        print(summary())
  2. 2Run it

    Make sure the venv is active (your prompt shows (.venv)).

    BASH
    python main.py
  3. 3Add a test

    Install pytest (pip install pytest), save this file, then run pytest -q. pytest finds files named test_*.py.

    test_main.py
    from main import summary
    
    def test_summary_text():
        assert "tasks completed" in summary()

✅ When it works you should see output like Figure 1.

5. Development configuration

Environment variables

Read settings with os.getenv(). python-dotenv loads a local .env file during development; on servers set variables in the systemd unit (EnvironmentFile=).

.env
API_URL=https://jsonplaceholder.typicode.com/todos
LOG_LEVEL=INFO

Key dependencies

Package / toolUsed for
venvIsolated environment per project (built in)
pipInstalls packages from PyPI
requirements.txt / pyproject.tomlList of dependencies
python-dotenvLoad .env in development
pytestTesting
ruffVery fast linter and formatter

Folder structure

project structure
py-demo/
├── .venv/            # virtual environment (git-ignored)
├── src/ or package/  # code for larger projects
├── tests/
├── main.py
├── requirements.txt
├── .env
└── pyproject.toml    # optional tool config

Essential commands

CommandWhat it does
python3 -m venv .venvCreate a virtual environment
source .venv/bin/activateActivate it (Windows: .venv\Scripts\activate)
pip install -r requirements.txtInstall all dependencies
pip freeze > requirements.txtSave exact versions
python -m pytestRun tests
deactivateLeave the venv

6. Production deployment

A Python program in production is usually either a long-running service (an API, a worker, a bot) or a scheduled job. Both run best under systemd on Linux. For web apps follow the Django, Flask or FastAPI guides, which add Gunicorn/Uvicorn and Nginx.

Server & hosting requirements

RequirementRecommendation
ServerUbuntu 24.04 VPS (Python 3.12 included), 1 GB RAM
IsolationA venv per app under /srv/app
Service managersystemd service or systemd timer / cron
Logsjournalctl or log files with rotation

Deployment steps

  1. 1Prepare an Ubuntu server

    Create a VPS (AWS EC2, DigitalOcean, Hostinger VPS, Linode …) with Ubuntu 24.04 LTS, at least 1 vCPU and 1–2 GB RAM. Log in with SSH, update the system and create a non-root user for the app.

    BASH
    ssh root@YOUR_SERVER_IP
    apt update && apt upgrade -y
    adduser deploy
    usermod -aG sudo deploy
    # copy your SSH key to the new user, then log in as deploy
    rsync --archive --chown=deploy:deploy ~/.ssh /home/deploy
    exit
    ssh deploy@YOUR_SERVER_IP
  2. 2Install Python on the server

    Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.

    BASH
    sudo apt install -y python3 python3-venv python3-pip
    sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app
  3. 3Upload the code and install dependencies

    Create the venv on the server – never copy a venv between machines.

    BASH
    git clone https://github.com/you/py-demo.git /srv/app
    cd /srv/app
    python3 -m venv .venv
    .venv/bin/pip install -r requirements.txt
    nano /srv/app/.env   # production settings
  4. 4Run it as a systemd service

    systemd starts the app on boot and restarts it on failure. Save the unit file, then enable it. Logs: journalctl -u py-demo -f.

    /etc/systemd/system/py-demo.service
    [Unit]
    Description=py-demo
    After=network.target
    
    [Service]
    User=deploy
    WorkingDirectory=/srv/app
    EnvironmentFile=/srv/app/.env
    ExecStart=/srv/app/.venv/bin/python /srv/app/main.py
    Restart=always
    RestartSec=5
    
    [Install]
    WantedBy=multi-user.target
  5. 5Start and enable the service

    Reload systemd, start the service now and on every boot, and check that it is active (running).

    BASH
    sudo systemctl daemon-reload
    sudo systemctl enable --now py-demo
    sudo systemctl status py-demo
    journalctl -u py-demo -f
  6. 6Or run it on a schedule

    For a job that runs and exits (e.g. every night at 02:30), use cron with the venv’s Python and log the output.

    OUTPUT
    crontab -e
    30 2 * * * cd /srv/app && .venv/bin/python main.py >> /var/log/py-demo.log 2>&1

🗺 The whole path from your code to the live site is drawn in the deployment diagram.

7. Images & screenshots

Illustrations drawn for this guide from the commands above. Product dashboards change often, so for screens such as cloud consoles follow the step text and the official documentation.

terminal$ python main.py90 of 200 tasks completed$ pytest -q. [100%]1 passed in 0.84s
Figure 1: terminal output of the sample Python project (section 4).
1Write + testlocally2git clone onserver3venv + pip install4systemd / cron5Logs in journalctl
Figure 2: production deployment flow (section 6).
py-demo/├── .venv/ # virtual environment (git-ignored)├── src/ or package/ # code for larger projects├── tests/├── main.py├── requirements.txt├── .env└── pyproject.toml # optional tool config
Figure 3: project folder structure (section 5).

8. Common errors & solutions

python is not recognised (Windows)

Re-run the installer and tick Add python.exe to PATH, or use the py launcher (py main.py).

ModuleNotFoundError: No module named 'requests'

The venv is not active or the package is not installed in it. Activate .venv and pip install -r requirements.txt.

error: externally-managed-environment when using pip on Ubuntu

Ubuntu protects the system Python (PEP 668). Create a venv and install packages inside it.

Windows: running scripts is disabled on this system

Allow local scripts for your user: Set-ExecutionPolicy -Scope CurrentUser RemoteSigned, then activate again.

Works locally, fails on the server

Different Python or package versions. Pin versions in requirements.txt and use the same Python minor version.

Best practices

  • One venv per project; never sudo pip install.
  • Pin versions and update them deliberately.
  • Use logging instead of print in services.
  • Format and lint with ruff; type-hint public functions.
  • Never commit .env files or keys – add them to .gitignore, keep a .env.example with dummy values, and store real secrets in the server or CI secret store.