Python虚拟环境pipenv,virtualvenv

先说virtualvenv

Python2,因为我默认的环境是Python2,所有切换至文件夹后,使用如下命令。

virtualenv --no-site-packages venv

使用

python -V#查看当前环境python的版本
which python#查看Python的路径

Python3呢?

virtualenv -p python3 envname

使用pipenv

virtualvenv是相对古老的一个了,有些过时了,比如说,你有时候如果不在requirements.txt文件中写入下载的包,你可能会不知道当前环境中有啥?面对这流行的npm等包管理工具,pipenv应运而生。它的一个明显的优点就是,有了一个文件,自动的记录当前环境使用的包。

以Python3为例,展示下用法,注意把路径中的dongweiming换成自己的用户名:

pip3 install pipenv --user  # 推荐安装在个人目录下
export PATH="/Users/dongweiming/Library/Python/3.6/bin:$PATH"  # 把用户目录下bin放在最前面,这样可以直接使用pipenv了

新建一个文件夹

❯ mkdir test_pipenv
❯ cd test_pipenv
❯ pipenv install  # 创建一个虚拟环境
Creating a virtualenv for this project…
...
Installing setuptools, pip, wheel...done.
Virtualenv location: /Users/dongweiming/.virtualenvs/test_pipenv-GP_s2TW5
Creating a Pipfile for this project…
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (c23e27)!
Installing dependencies from Pipfile.lock (c23e27)…
      ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 0/0 — 00:00:00
To activate this project's virtualenv, run the following:
 $ pipenv shell
❯ which python3
/usr/local/Cellar/python3/3.6.1/bin/python3  # 还是mac自带的Python
❯ pipenv shell  # 激活虚拟环境
Spawning environment shell (/bin/zsh). Use 'exit' to leave.
source /Users/dongweiming/.virtualenvs/test_pipenv-GP_s2TW5/bin/activate
❯ which python3  # 已经在虚拟环境里了
/Users/dongweiming/.virtualenvs/test_pipenv-GP_s2TW5/bin/python3
❯ exit  # 退出虚拟环境
❯ which python3
/usr/local/Cellar/python3/3.6.1/bin/python3

查看当前文件多了什么

❯ ls
Pipfile  Pipfile.lock

Pipfile.lock中文件就记录了下载了哪些包。至于卸载和查看包之间的依赖关系,可以查看董伟明的文章

参考文章

廖雪峰的官方网站
董伟明的文章
Using Python 3 in virtualenv

    原文作者:Manuone
    原文地址: https://www.jianshu.com/p/24a1561c18c3
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞