$ ls ~yifei/notes/

Python 的虚拟环境

Posted on:

Last modified:

In Python 3, there is a virtual environment shipped with the standard lib called venv.

To create a new venv, you can simply call:

python3 -m venv <venv-name>

To activate the venv, you need to source the generated shell script:

source <venv-name>/bin/activate

Note: the generated activate script contains directory information based on your local paths, so it's NOT portable to other machines.

To deactivate it:

deactivate

But, in most cases, we don't really care about the name of the virtualenv, so let's simply call it .venv, and you can add the following to your .bashrc for convenience:

DEFAULT_VENV_NAME=".venv"
alias create-venv="python3 -m venv $DEFAULT_VENV_NAME"
alias activate="source $DEFAULT_VENV_NAME/bin/activate"

After you activate your venv, there would be a "venv" sign in your shell prompt. You can see that python3 and pip3 is set to the venv copy of python3 by running:

which python3
.venv/bin/python3

If you run pip install, the packages will be installed in your local venv directory, so no sudo needed!

Since the venv directory is not portable, the best practice would be to save your dependencies in a requirements.txt file.

升级 venv 中的 Python 版本

首先,你需要跳出来 venv, 到一个全局环境中,然后执行:

python3 -m venv --upgrade YOUR_VENV_DIRECTORY

这样就可以升级到对应的 Python 版本啦

移动虚拟环境

venv 把路径直接写到了 bin 中,如果重命名了文件夹,则需要手工替换一下,以使用 sd 为例:

sd "OLD_DIR" "NEW_DIR" .venv/bin/*

Use system packages

Change in .venv/pyvenv.cfg file:

- include-system-site-packages = false
+ include-system-site-packages = true

参考

  1. https://stackoverflow.com/questions/2170252/can-existing-virtualenv-be-upgraded-gracefully

© 2016-2022 Yifei Kong. Powered by ynotes

All contents are under the CC-BY-NC-SA license, if not otherwise specified.

Opinions expressed here are solely my own and do not express the views or opinions of my employer.