How to Use `venv` in Python 3.12
This story simply explains how to use venv
in Python 3.12 (precisely speaking, Python 3.7 or later).
Environment
- Python 3.12.1
Premises
venv
is a module to create isolated environments for managing project-specific packages. In other words, it enables us to create separate pip
environments.
Actions
0: Go to the directory where you want to set up venv
cd <path/to/dir>
1: Create a new environment
.venv
is a directory to store everything about the virtual environment. The name can be anything, but I personally prefer using .venv
.
python -m venv .venv
If you use git
, you may want to add this line, .venv/
, to .gitignore
.
2: Activate the environment
Mac OS and Windows have different commands.
# For Mac OS
source .venv/bin/activate
# For Windows PowerShell
.venv\Scripts\Activate.ps1
If the environment is successfully activated, every line of the Terminal shows (.venv)
, or the name you defined at Step 1.
3: Use pip
to install packages
Use these pip
commands to install packages. Usually we use requirements.txt
to install packages required by each project.
# Install packages written in requirements.txt
pip install -r requirements.txt
# Create requirements.txt based on the current environment
pip freeze > requirements.txt
If you want to install one by one, just write a package name after pip install
. Note that <package name>
can be <package name>==<version>
, such as numpy==2.1.3
, if you need a specific version.
# Install a new package
pip install <package name>
# Upgrade a package
pip install -U <package name>
# Forcely reinstall a package (You may want to do this when there is something wrong.)
pip install --force-reinstall <package name>
Additionally, pip
has these helpful functions.
# Show all installed packages
pip list
# Show detailed info about a specific installed package
pip show <package name>
#### Example: the result of `pip show ipython` ####
# Name: ipython
# Version: 8.15.0
# Summary: IPython: Productive Interactive Computing
# Home-page: https://ipython.org
# Author: The IPython Development Team
# Author-email: ipython-dev@python.org
# License: BSD-3-Clause
# Location: /opt/homebrew/lib/python3.12/site-packages
# Requires: appnope, backcall, decorator, jedi, matplotlib-inline, pexpect, pickleshare, prompt-toolkit, pygments, stack-data, traitlets
# Required-by: ipykernel
4: Deactivate the environment
Very simple.
deactivate
5: Remove the environment
This is also straightforward. Remove the .venv
directory.
# Assume the current directory has `.venv`
# For Mac OS
rm -rf .venv
# For Windows PowerShell
Remove-Item -Path ".venv" -Recurse -Force
Actions for VSCode & Jupyter Notebook
1: Open a New Jupyter Notebook
Open a new .ipynb
file and click “Select Kernel” on the right.
2: Click “Python Environments…”
3: Choose a Python Environment
The path to the venv
environment should be shown like .venv/bin/python
.