跳转至

How to Set up Python Virtual Environments#

Installation#

On macOS, run:

brew install pyenv pyenv-virtualenv

Configuration#

Add the following lines to ~/.zprofile:

# pyenv
export PYENV_ROOT="$HOME/.pyenv"
export PATH=$PYENV_ROOT/shims:$PATH
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

Usage#

pyenv versions                              # View installed Python versions
pyenv install -v $VERSION                   # Install a specific version of Python
pyenv virtualenv $VERSION $PROJECT_NAME     # Create a virtual environment with a specific Python version
pyenv activate $PROJECT_NAME                # Activate the virtual environment for the project
pyenv deactivate                            # Deactivate the current virtual environment

# ... More ...

pyenv --help

Example#

$ gh repo clone keepwow/ktmm
$ cd ktmm
$ pyenv virtualenv 3.12.2 ktmm
$ pyenv shell ktmm

(ktmm) pip install -r requirements.txt
...

Notes#

A project is not a directory path; it's more about managing versions at the system level. You can create a project path first and then use the pyenv activate PROJ command to achieve the desired effect, which is different from virtualenv.


Tip: Using Pyenv with a Chinese Mirror for Python Installation#

pyenv does not have a configuration option for mirror sites, but we can work around this.

Principle#

The process of pyenv installing Python involves downloading packages to the ~/.pyenv/cache directory before installation.

Solution#

  1. Manually download the package to a specified directory.
  2. Execute pyenv install.

Example#

% mkdir -pv ~/.pyenv/cache
% v=3.8.5; curl -C - -L https://mirrors.huaweicloud.com/python/$v/Python-$v.tar.xz -o ~/.pyenv/cache/Python-$v.tar.xz; pyenv install $v

General Solution#

  • Create a function and add it to the ~/.zshrc file for easy use. Note the usage of the curl command.
function pyenv-install() {
    v=$1
    echo 'Installing Python' $v
    curl -C - -L https://repo.huaweicloud.com/python/$v/Python-$v.tar.xz -o ~/.pyenv/cache/Python-$v.tar.xz
    pyenv install $v
}
  • Now you can call the pyenv-install function to install the desired Python version.
pyenv-install 3.9.2