هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
The quick answer
Step by step
- Choose the Python version — the system one, or a newer one from the distro:
python3 --version
dnf -y install python3.12
python3.12 -m venv /opt/shop/.venv- Create and use the venv (quick answer). After
source .venv/bin/activatethe commandspythonandpipare the venv's (the prompt shows(.venv)). Activation only changesPATHfor this shell — you can also call the venv's Python directly, without activating:
/opt/shop/.venv/bin/python -m pip install --upgrade pip
/opt/shop/.venv/bin/pip install -r /opt/shop/requirements.txt- Pin your packages so every server gets the same versions:
pip install flask gunicorn psycopg[binary]
pip freeze > requirements.txt
head -3 requirements.txt
blinker==1.9.0
click==8.1.8
flask==3.1.0Commit requirements.txt, not the .venv folder (add .venv/ to .gitignore).
- Use it in a systemd service or cron job — always the full path to the venv's binaries:
[Service]
User=shop
WorkingDirectory=/opt/shop
ExecStart=/opt/shop/.venv/bin/gunicorn --bind 127.0.0.1:8000 app:app15 3 * * * shop /opt/shop/.venv/bin/python /opt/shop/jobs/cleanup.py- Command-line tools you want everywhere (ansible-lint, yamllint, httpie) →
pipxgives each its own venv:
pipx install yamllint- uv — a much faster replacement for
pipandvenv(same files, same idea):
uv venv .venv
uv pip install -r requirements.txt- Rebuild instead of repair: a broken venv is deleted and created again from
requirements.txt— that is the point of it.
Check that it worked
Common problems
| Problem | Cause | Fix |
|---|---|---|
error: externally-managed-environment | New Debian/Ubuntu protect the system Python (PEP 668). | Use a venv (or pipx). Do not use --break-system-packages. |
The virtual environment was not created successfully because ensurepip is not available | python3-venv missing. | apt-get install python3-venv. |
ModuleNotFoundError in the service | The service uses the system Python. | ExecStart with /opt/app/.venv/bin/…. |
| The venv breaks after a Python upgrade | The venv points to the old Python binary. | Delete and recreate it from requirements.txt. |
Build errors for packages like psycopg2 | Needs compilers and headers. | Use binary wheels (psycopg[binary]) or install gcc and *-devel packages. |
The .venv folder ended up in Git | Not ignored. | Add .venv/ to .gitignore; remove it from the repo. |
Go further
- Command pages: pip, systemctl.
- Next how-tos: Create a systemd service for your app, Write a safe Bash script, Write a small and safe Dockerfile.
- Full guide: Install Python for DevOps work. Learn it: pip in the build tools.
1Why not install packages with sudo pip install?
They mix with the system's packages and can break system tools; new distros even refuse it.
2How does a systemd service use a venv?
ExecStart points to the venv's binary, for example /opt/shop/.venv/bin/gunicorn.