Moving a Python virtual environment (venv) to another computer

This post documents the correct way to move a Python project that is utilising virtual environments.

Step 1 - Document your required Python packages

Open up your Python project (I'm using VS Code) and browse to the project's root folder in the command terminal. Ensure that your virtual enviroment is currently active, which in VS Code should be indicated in the bottom-left (notice the mention of .venv):

In the terminal enter:

pip freeze > requirements.txt

A requirements.txt file should appear in your project directory. This file documents the packages and their specific version that your Python project depends on. Leave the requirements.txt file where it is.

A snippet of my requirements.txt file

Step 2 - Copy your project files

Copy your Python project files to the new location, but do not copy your virtual environment (.venv) folder. We will be re-creating your virtual environment in the new location.

Step 3 - Recreate your virtual environment

In your new location, open your project and create a new virtual environment. If using VS Code, refer to the document on creating and using virtual environments for exact details, but its likely the command:

python3 -m venv .venv or python -m venv .venv or py3 -m venv .venv

Again, ensure your virtual environment is active per Step 1.

Step 4 - It's rarely that easy...

Every time I attempted to move my project, I ran into the same issue! When trying to re-install the dependent packages from requirements.txt, they would install into the global Python directory instead of the venv (our virtual) directory...

Notice that the packages are installing into the global python directory instead...

To resolve, we must ensure that our virtual environment is indeed active. Enter one of the following commands in your terminal at your project's root directory (it seems to change dependent on the OS):

.\.venv\Scripts\activate

or

venv/bin/activate or source venv/bin/activate

I often now see (.venv) appear in the terminal at the start of each line, indicating properly that .venv is now active:

Use the requirements.txt file to re-populate our virtual environment with the required packages and their specific versions. In the command terminal enter:

pip install -r requirements.txt

If successful, you should should see the newly installed packages under your virtual environment (.venv) directory .venv\Lib\site-packages:

Installed packages for our newly created virtual environment. Note that this is on Windows; other OS may have a slightly different directory structure.

Your project should now compile, thus you have successfully migrated your Python project.

If still unsuccessful, a Google for "pip not installing packages to venv" is your best hope I'm afraid.