pipenv -- python 搭建虚拟环境

由于py2 和 py3 上对语法的不兼容,对于使用者而言,如果同时安装了 2个版本,那么就会导致环境的混淆,并且当我们在同一台开发机进行开发不同项目时,也许对相同的模块有不同版本的需求,那么此时就需要我们进行运行环境的隔离

之前我们使用环境隔离基本用的都是virtualenv,但是当我们需要导出requests.txt 时,如果模块有改动,那么就需要重新修改,实在是不智能,如能够及时的维护requests.txt呢,那么pipenv 就体现了十足的功能

一、安装

pip install pipenv

 

二、创建虚拟环境(前提是你的服务器此时已经安装好对应的Python版本)

# 创建python3环境
pipenv --three
# 创建python2环境 pipenv --two 

  之后会看到对应的输出(以py3示例)

[root@spider]# pipenv --three
Creating a virtualenv for this project…
Pipfile: ./spider/Pipfile
Using /usr/bin/python3 (3.6.5) to create virtualenv…
⠸ Creating virtual environment...Already using interpreter /usr/bin/python3
Using base prefix '/data/ops/app/python3'
New python executable in /root/.local/share/virtualenvs/spider-/bin/python3
Also creating executable in /root/.local/share/virtualenvs/spider-/bin/python
Installing setuptools, pip, wheel...
done.
✔ Successfully created virtual environment! 
Virtualenv location: /root/.local/share/virtualenvs/spider-
Creating a Pipfile for this project…

  此时证明你已经创建成功

 

三、进入虚拟环境

pipenv shell

  如下输出,看到括号内的环境名字代表已经创建并成功进入

[root@spider]# pipenv shell
Launching subshell in virtual environment…
 . /root/.local/share/virtualenvs/spider-/bin/activate
[root@spider]#  . /root/.local/share/virtualenvs/spider-/bin/activate
(spider) [root@spider]# 

  此时目录下会多Pipfile文件,查看下

(spider) [root@spider]# cat Pipfile 
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]

[requires]
python_version = "3.6"

 

四、安装相关模块并加入到Pipfile

  随着项目的开发当我们新安装各种包时,pipenv 会自动帮我们生成Pipfile 和 Pipfile.lock文件

  以安装lxml示例

(spider) [root@ spider]# pipenv install lxml
Installing lxml…
✔ Installation Succeeded 
Pipfile.lock (e067e5) out of date, updating to (ca72e7)…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
✔ Success! 
Updated Pipfile.lock (e067e5)!
Installing dependencies from Pipfile.lock (e067e5)…
     ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 2/2 —

 此时cat Pipfile 会发现新安装的lxml已经自动加入到了Pipfile文件中

(spider) [root@spider]# cat Pipfile
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]

[packages]
redis = "*"
lxml = "*"

[requires]
python_version = "3.6"

  当我们需要移植环境,下载所有依赖包时,只需要执行pipenv install 就可以自动下载所有Pipfile中的包(在Pipfile 和 Pipfile.lock目录下)

pipenv install

五、卸载全部包并从Pipfile中移除

pipenv uninstall --all 

 

六、退出环境

exit

 

温馨提示

  如果在当前环境中的子目录想在重新创建一个虚拟环境的话,是不能直接按照上面操作成功的,因为在pipenv 中是默认找到父及目录的Pipfile 进行加载环境,如果非要重新创建新的,那么就退出父及,重新创建吧

good bye

猜你喜欢

转载自www.cnblogs.com/yidada/p/10616679.html