python 3 使用 pipenv 进行依赖管理与项目隔离

文章目录

    pipenv 吸引我的地方

    • 命令参数简单好记,感觉更像 PHP 的 composer
    • pip 与 virtualenv 合并为一个命令
    • 使用 Pipfile 替代 requirements.txt,管理依赖更方便

    但是,似乎当前更流行 使用 conda 管理 python 开发环境

    安装 pipenv

    系统环境

    • Ubuntu 20.04
    • Python 3.8
      sudo apt install pipenv

    Ubuntu 18.04 安装 pipenv

    如何是 Ubuntu 18.04 可能会报错,参考 E: Unable to locate package pipenv

    使用 pipenv 安装依赖

    以安装常用的 requests 依赖为例,在一个新项目根目录下执行:

    > pipenv install requests
    
    Creating a Pipfile for this project…
    Installing requests…
    Looking in indexes: https://pypi.python.org/simple
    Requirement already satisfied: requests in /home/zhongwei/.local/share/virtualenvs/crawler-X1fRJW1f/lib/python3.8/site-packages (2.22.0)
    
    Adding requests to Pipfile's [packages]…
    Pipfile.lock not found, creating…
    Locking [dev-packages] dependencies…
    Locking [packages] dependencies…
    Updated Pipfile.lock (4fe234)!
    Installing dependencies from Pipfile.lock (4fe234)…
      🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 5/5 — 00:00:02
    To activate this project's virtualenv, run the following:
     $ pipenv shell
    

    执行完毕之后,会发现目录下多了两个文件:

    > ls
    Pipfile*  Pipfile.lock*
    

    直观感受:

    • 相对 pip 来说,pipenv 明显要简洁很多。install 依赖时,自动就生成了依赖管理文件。而不用像 requirements.txt 那样,记不住命令。
    • 从创建的虚拟目录来看,自动与当前项目关联上了。

    Pipfile 的格式

    > cat Pipfile
    [[source]]
    url = "https://pypi.python.org/simple"
    verify_ssl = true
    name = "pypi"
    
    [packages]
    requests = "*"
    
    [dev-packages]
    
    [requires]
    python_version = "3.8"
    

    可以看到,依赖被记录到了 packages 区域。

    Shell

    pipenv shell will spawn a shell with the virtualenv activated.

    所以,在本地开发调试时,应该是先进入 pipenv shell,然后执行 python3 xxx.py 来调试。

    执行一下,看看效果:

    > pipenv shell
    Spawning environment shell (/usr/bin/fish). Use 'exit' to leave.
    Welcome to fish, the friendly interactive shell
    Type `help` for instructions on how to use fish
    zhongwei@PCMICRO-27VTFD1 /m/d/w/c/crawler (master)> source /home/zhongwei/.local/share/virtualenvs/crawler-X1fRJW1f/bin/activate.fish
    (crawler-X1fRJW1f) zhongwei@PCMICRO-27VTFD1 /m/d/w/c/crawler (master)>
    

    线上如何运行 Python 脚本

    pipenv run python main.py
    

    git clone 之后,如何快速部署/搭建开发环境

    // TODO
    直接 pipenv install ?

    SOP 标准操作流程

    1. pipenv shell 进入独立的虚拟环境
    2. pipenv install xxx 安装依赖
    3. python xxx.py 执行调试

    参考

    https://pypi.org/project/pipenv/

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式