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 need | Version / notes |
|---|---|
| Python | A supported 3.x release (3.11 or newer recommended) – check with python3 --version |
| pip + venv | Included with Python (on Ubuntu install python3-venv) |
| Editor | VS Code with the Python extension, or PyCharm |
| Terminal | PowerShell / Terminal / bash |
3. Local setup
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 --version2Create a project folder
Keep code, venv and requirements together.
BASHmkdir py-demo && cd py-demo3Create and activate a virtual environment
A venv keeps each project’s packages separate. Activate it in every new terminal.
BASHpython3 -m venv .venv # macOS / Linux source .venv/bin/activate # Windows (PowerShell) .venv\Scripts\Activate.ps1 python -m pip install --upgrade pip4Install packages and record them
Install what you need, then freeze exact versions.
BASHpip install requests python-dotenv pip freeze > requirements.txt
4. Create & run a project
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.pyimport 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())2Run it
Make sure the venv is active (your prompt shows
(.venv)).BASHpython main.py3Add a test
Install pytest (
pip install pytest), save this file, then runpytest -q. pytest finds files namedtest_*.py.test_main.pyfrom 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=).
API_URL=https://jsonplaceholder.typicode.com/todos
LOG_LEVEL=INFOKey dependencies
| Package / tool | Used for |
|---|---|
venv | Isolated environment per project (built in) |
pip | Installs packages from PyPI |
requirements.txt / pyproject.toml | List of dependencies |
python-dotenv | Load .env in development |
pytest | Testing |
ruff | Very fast linter and formatter |
Folder 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 configEssential commands
| Command | What it does |
|---|---|
python3 -m venv .venv | Create a virtual environment |
source .venv/bin/activate | Activate it (Windows: .venv\Scripts\activate) |
pip install -r requirements.txt | Install all dependencies |
pip freeze > requirements.txt | Save exact versions |
python -m pytest | Run tests |
deactivate | Leave 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
| Requirement | Recommendation |
|---|---|
| Server | Ubuntu 24.04 VPS (Python 3.12 included), 1 GB RAM |
| Isolation | A venv per app under /srv/app |
| Service manager | systemd service or systemd timer / cron |
| Logs | journalctl or log files with rotation |
Deployment steps
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.
BASHssh 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_IP2Install Python on the server
Ubuntu 24.04 ships Python 3.12. Install venv support and create the app user’s folder.
BASHsudo apt install -y python3 python3-venv python3-pip sudo mkdir -p /srv/app && sudo chown deploy:deploy /srv/app3Upload the code and install dependencies
Create the venv on the server – never copy a venv between machines.
BASHgit 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 settings4Run 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.target5Start and enable the service
Reload systemd, start the service now and on every boot, and check that it is active (running).
BASHsudo systemctl daemon-reload sudo systemctl enable --now py-demo sudo systemctl status py-demo journalctl -u py-demo -f6Or 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.
OUTPUTcrontab -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.
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
logginginstead ofprintin services. - Format and lint with ruff; type-hint public functions.
- Never commit
.envfiles or keys – add them to.gitignore, keep a.env.examplewith dummy values, and store real secrets in the server or CI secret store.