Python projects can need different versions of third-party packages. The built-in venv module creates a virtual environment for each project, keeping its packages organized and helping avoid version conflicts. A virtual environment is not complete isolation. section 2.1.1
To set up a FastAPI project:
- Create a project folder, navigate into it, and run python3 -m venv venv on macOS or Linux, or python -m venv venv on Windows. The new venv directory holds the environment. section 2.1.1
- Activate it with source venv/bin/activate on macOS or Linux, or .\venv\Scripts\activate on Windows. Activate it again whenever you return to work on the project; an editor may do this for you. section 2.1.1
- Install dependencies into the activated environment with python -m pip install fastapi, or install the project's package list with python -m pip install -r src/requirements.txt. section 2.1.1
Listing 2.2 Creating a Python virtual environment
# In our Python project folder cd ~/Dev/roadtok8s/py/ # Windows users python -m venv venv # Linux or macOS users python3 -m venv venv
The command runs venv through the chosen Python interpreter; the final venv names the directory to create. section 2.1.1
On an Ubuntu server, install python3-venv if the venv module is unavailable, then create a server-side environment with python3 -m venv /opt/venv/. Deployment commands can use /opt/venv/bin/python directly to install requirements without first activating the environment. section 3.4.1
Listing 3.18 Installing Python packages with absolute paths
/opt/venv/bin/python -m pip install -r \
/opt/venv/roadtok8s/py/src/requirements.txt
The absolute path selects the server environment's Python when installing the application's requirements. section 3.4.1
