Managing Python Virtual Environments in VS Code on macOS
Creating a Virtual Environment
Use the venv module to set up an isolated workspace:
python3 -m venv myenv
myenv is the name of the environment folder. Make sure Python 3 is available on your system.
Activating the Environment
macOS / Linux:
source myenv/bin/activate
Windows:
.\myenv\Scripts\activate
The terminal prompt will change to include the environment name, indicating its active.
Deactivating and Removing
Deactivate the environment before deletion:
deactivate
Then remove the entire folder:
rm -rf myenv
Package Management
Install packages using pip:
pip install numpy==1.24.0
Use a PyPI mirror for faster downloads:
pip install numpy==1.24.0 -i https://pypi.tuna.tsinghua.edu.cn/simple/
Common mirrors:
- Alibaba: http://mirrors.aliyun.com/pypi/simple/
- USTC: https://pypi.mirrors.ustc.edu.cn/simple/
- Douban: http://pypi.douban.com/simple/
- Tsinghua: https://pypi.tuna.tsinghua.edu.cn/simple/
To install a package from a local source:
pip install -e /path/to/package
Freezing and Restoring Dependencies
Export the current package list:
pip freeze > requirements.txt
Reinstall the exact same versions on another machine:
pip install -r requirements.txt
Using the Environment in VS Code
Open the integrated terminal with Ctrl+`` (backtick) or through the **Terminal** menu. VS Code can automatically activate the environment if the correct Python interpreter is selected. To choose the interpreter, use the command palette (Cmd+Shift+P) and run **Python: Select Interpreter**, then pick the one located inside myenv/bin/python` (macOS). The terminal will activate the enviroment on launch.