A Python virtual environment keeps a project’s packages separate from other projects and the system’s Python installation. This guide creates one for command-line work on a hosting server.

Why use a Python virtual environment

Separate environments allow applications to use different package versions. They do not provide a security sandbox or automatically configure a hosted web application.

Step 1: Check Python installation

Run:

python3 --version

On a server you administer, install the supported Python and environment tools if needed. Debian and Ubuntu provide python3-venv; other distributions use different package names. On shared hosting, use the provider’s approved Python tools without attempting system package installation.

Step 2: Create a virtual environment

From the project’s directory, create a new environment:

python3 -m venv .venv

Use a fresh target directory. If the host supplies a Python Selector environment, use that environment instead of nesting another one inside it.

Step 3: Activate the virtual environment

For Bash on Linux or macOS:

source .venv/bin/activate

For Windows PowerShell:

.\.venv\Scripts\Activate.ps1

For Windows Command Prompt:

.venv\Scripts\activate.bat

On Windows, create the environment using the installed Python command, commonly py -m venv .venv.

Step 4: Install packages inside the virtual environment

Use the project’s requirements file:

python -m pip install -r requirements.txt
python -m pip list

To record the installed versions without overwriting an existing requirements file:

python -m pip freeze > requirements-installed.txt

Review that file before adopting it as the project’s dependency list.

Step 5: Deactivate the virtual environment

Run:

deactivate

Step 6: Best practices for hosting servers

Back up application code, configuration and dependency specifications. Recreate the environment when moving the project or changing its Python installation; virtual environments are generally not portable.

Test dependency updates before production deployment. A web service must be configured to use the environment’s interpreter; activating it in an SSH session does not change an already running service.