使用Pipenv重新审视Python打包

总览

Python是目前最友好但功能最强大的语言之一。 初学者很容易上手,但功能强大,并且广泛用于科学编程,Web应用程序编程和DevOps等各种领域。 但是Python的最弱点之一是它对打包复杂的应用程序及其依赖项的支持。

多年来,为改善这种状况做出了许多努力。 2017年8月,我写了一篇关于Python打包技术的教程: 如何用Python 编写,打包和分发库

仅仅四个月,小镇上就有一个新玩家。 Pipenv现在是PyPA(Python包装管理局)官方推荐的包装工具。 在本教程中,您将了解为什么Pipenv为Python开发人员显着改善了打包状态和整体开发工作流程,以及如何有效地使用它。

人类的Python开发工作流程

Pipenv的目标是在管理依赖项和虚拟环境时改善Python开发人员的开发工作流程。 这是勤劳的Kenneth Reitz的另一个很好的库,该库以请求包(人类的HTTP)而闻名,但还编写了其他一些出色的包。

我们还需要另一种包装工具吗?

是的,我们做到了! Pipenv从现代程序包管理实践中吸取了一页内容,并将其导入Python世界。

安装Pipenv

您可以使用pip install pipenv 。 使用表情符号,您将获得不错的输出:

$ pip install pipenv
✨🍰✨

您只需要执行一次。 如果没有安装pip,则可以使用以下引导程序命令: $ curl https://github.com/pypa/pipenv/blob/master/get-pipenv.py | python | python

Pipfile和Pipfile.lock

Pipenv可以为您创建一个空的虚拟环境。 这是一个快速演示:

~/git > mkdir testpipenv
~/git > cd testpipenv
~/git/testpipenv > pipenv --three

Output:

Creating a virtualenv for this project…
Using /usr/local/bin/python3 to create virtualenv…
⠋Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy/bin/python3.6
Also creating executable in /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy
Creating a Pipfile for this project…

这将创建一个没有依赖项的空Pipfile。 但是,由于您可能要为项目安装一些软件包,因此只需使用pipenv安装软件包,它将自动创建虚拟环境。 例如:

~/git/testpipenv > pipenv install requests

Output:


Installing requests…
Collecting requests
  Using cached requests-2.18.4-py2.py3-none-any.whl
Collecting idna<2.7,>=2.5 (from requests)
  Using cached idna-2.6-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests)
  Using cached certifi-2017.11.5-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests)
  Using cached urllib3-1.22-py2.py3-none-any.whl
Installing collected packages: idna, chardet, certifi, urllib3, requests
Successfully installed certifi-2017.11.5 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22

Adding requests to Pipfile's [packages]…
  PS: You have excellent taste! ✨ 🍰 ✨
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (7b8df8)!

细节水平极佳,并且也使用漂亮的颜色。 这是生成的Pipfile:

[[source]]

url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"


[dev-packages]



[packages]

requests = "*"


[requires]

python_version = "3.6"

Pipfile跟踪项目的顶级依赖关系-在这里,仅是requests = "*" 。 它使用TOML作为格式,这是当今配置文件(Rust的货物,Python的PEP-518)的流行选择。

另一方面,Pipefile.lock文件是一个JSON文件,它指定一些元数据以及所有递归依赖项(顶级依赖项及其依赖项)的确切版本(包括哈希)。 这是Pipfile.lock文件:

{
    "_meta": {
        "hash": {
            "sha256": "33a0ec7c8e3bae6f62dd618f847de92ece20e2bd4efb496927e2524b9c7b8df8"
        },
        "host-environment-markers": {
            "implementation_name": "cpython",
            "implementation_version": "3.6.3",
            "os_name": "posix",
            "platform_machine": "x86_64",
            "platform_python_implementation": "CPython",
            "platform_release": "16.7.0",
            "platform_system": "Darwin",
            "platform_version": "Darwin Kernel Version 16.7.0: Wed Oct  4 00:17:00 PDT 2017; root:xnu-3789.71.6~1/RELEASE_X86_64",
            "python_full_version": "3.6.3",
            "python_version": "3.6",
            "sys_platform": "darwin"
        },
        "pipfile-spec": 6,
        "requires": {
            "python_version": "3.6"
        },
        "sources": [
            {
                "name": "pypi",
                "url": "https://pypi.python.org/simple",
                "verify_ssl": true
            }
        ]
    },
    "default": {
        "certifi": {
            "hashes": [
                "sha256:244be0d93b71e93fc0a0a479862051414d0e00e16435707e5bf5000f92e04694",
                "sha256:5ec74291ca1136b40f0379e1128ff80e866597e4e2c1e755739a913bbc3613c0"
            ],
            "version": "==2017.11.5"
        },
        "chardet": {
            "hashes": [
                "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691",
                "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae"
            ],
            "version": "==3.0.4"
        },
        "idna": {
            "hashes": [
                "sha256:8c7309c718f94b3a625cb648ace320157ad16ff131ae0af362c9f21b80ef6ec4",
                "sha256:2c6a5de3089009e3da7c5dde64a141dbc8551d5b7f6cf4ed7c2568d0cc520a8f"
            ],
            "version": "==2.6"
        },
        "requests": {
            "hashes": [
                "sha256:6a1b267aa90cac58ac3a765d067950e7dbbf75b1da07e895d1f594193a40a38b",
                "sha256:9c443e7324ba5b85070c4a818ade28bfabedf16ea10206da1132edaa6dda237e"
            ],
            "version": "==2.18.4"
        },
        "urllib3": {
            "hashes": [
                "sha256:06330f386d6e4b195fbfc736b297f58c5a892e4440e54d294d7004e3a9bbea1b",
                "sha256:cc44da8e1145637334317feebd728bd869a35285b93cbb4cca2577da7e62db4f"
            ],
            "version": "==1.22"
        }
    },
    "develop": {}

如果要查看所有依赖pipenv graph ,请输入: pipenv graph

~/git/testpipenv > pipenv graph
requests==2.18.4
  - certifi [required: >=2017.4.17, installed: 2017.11.5]
  - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4]
  - idna [required: <2.7,>=2.5, installed: 2.6]
  - urllib3 [required: >=1.21.1,<1.23, installed: 1.22]

在Pipenv中使用已安装的软件包

使用Pipenv安装软件包后,就可以在虚拟环境中对其进行访问,就像使用标准软件包一样(就像通过pip进行安装一样)。 唯一的预防措施是必须使用虚拟环境解释器。 Pipenv提供了两个有用的命令: runshell

您使用pipenv run python <your program>.py运行程序,并使用pipenv shell使用虚拟环境Python解释器启动新的shell。 这是使用shell命令启动交互式Python会话的方法,该会话使用已安装的请求包从REST API获取当天的报价。 虚拟环境已激活,启动Python会在可用requests地方使用正确的解释器。

~/git/testpipenv > pipenv shell
Spawning environment shell (/bin/bash). Use 'exit' to leave.
source /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy/bin/activate
~/git/testpipenv > source /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy/bin/activate
(testpipenv-0GShD6dy) ~/git/testpipenv > python
Python 3.6.3 (default, Nov 19 2017, 16:39:12)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>> r = requests.get('https://quotes.rest/qod')
>>> r.ok
True
>>> r.json()
{'success': {'total': 1}, 'contents': {'quotes': [{'quote': 'Hang Out with People Who are Better than You.', 'author': 'Warren Buffett', 'length': None, 'tags': ['getting-better', 'inspire', 'people'], 'category': 'inspire', 'title': 'Inspiring Quote of the day', 'date': '2018-01-03', 'id': None}], 'copyright': '2017-19 theysaidso.com'}}
>>> quote = r.json()['contents']['quotes'][0]['quote']
>>> author = r.json()['contents']['quotes'][0]['author']
>>> print(f'{quote} ~~ {author}')
Hang Out with People Who are Better than You. ~~ Warren Buffett
>>>

从requirements.txt导入

如果您要迁移带有requirements.txt的现有项目,Pipenv可以帮助您。 只需: pipenv install -r <path/to/requirements.txt>

您所有的依赖项都将导入到Pipfile中。 要实际安装依赖项并生成Pipfile.lock,需要使用pipenv install 。 确认一切正常后,您可以删除requirements.txt文件。

如果您的requirements.txt位于创建虚拟环境的同一目录中,则Pipenv将自动生成Pipfile。 但要注意,如果您的requirements.txt文件包含固定版本,那么它们也会固定在Pipfile中。 在Pipenv世界中,固定应该发生在Pipfile.lock文件中。 Pipenv将给予友好的提醒。 见下文:

~/git/testpipenv > cat requirements.txt
requests==2.18.4
~/git/testpipenv > pipenv --three
Creating a virtualenv for this project…
Using /usr/local/bin/python3 to create virtualenv…
⠋Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy/bin/python3.6
Also creating executable in /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: /Users/gigi.sayfan/.local/share/virtualenvs/testpipenv-0GShD6dy
Requirements.txt found, instead of Pipfile! Converting…
Warning: Your Pipfile now contains pinned versions, if your requirements.txt did.
We recommend updating your Pipfile to specify the "*" version, instead.

这是Pipfile中的固定版本,建议更改为“ *”:

[packages]

requests = "==2.18.4"

现在安装依赖项:

~/git/testpipenv > pipenv install
Pipfile.lock not found, creating…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (0b0daf)!
Installing dependencies from Pipfile.lock (0b0daf)…
  🐍   ▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉▉ 5/5 — 00:00:01
To activate this project's virtualenv, run the following:
 $ pipenv shell
~/git/testpipenv >

可编辑的依赖关系

您可以告诉Pipenv将路径安装为可编辑。 当您依赖于正在开发的软件包并且想要依赖于源软件包而无需在每次进行更改时都实际安装它们时,这将很有用。 特别是,当您在其中工作时,它对于当前目录很有用。 为此,请使用-e--dev标志:

> pipenv install '-e .' --dev

您需要具有正确的setup.py文件。

使用Pipenv管理环境

您已经看到了Pipenv可以为您做的很多事情。 让我们更深入地研究一些其他命令和选项。

安装套件

pipenv install命令支持多个选项:

  • --dev :从Pipfile.lock安装develop和默认软件包。
  • --system :使用系统pip命令,而不要使用virtualenv中的命令。
  • --ignore-pipfile :忽略Pipfile并从Pipfile.lock安装。
  • --skip-lock :忽略Pipfile.lock并从Pipfile安装。 此外,请勿写出反映对Pipfile所做更改的Pipfile.lock。

根据您的工作流程和首选项,您可能需要在不同时间使用这些选项中的一个或多个。

卸载软件包

要卸载依赖项,请输入: pipenv uninstall <package name> 。 例如:

~/git/testpipenv > pipenv uninstall requests
Un-installing requests…
Uninstalling requests-2.18.4:
  Successfully uninstalled requests-2.18.4

Removing requests from Pipfile…
Locking [dev-packages] dependencies…
Locking [packages] dependencies…
Updated Pipfile.lock (625834)!

请注意,即使将其固定在Pipfile中,卸载时也不必指定“ requests == 2.8.14”。

锁定依赖项

如果要生成当前依赖关系的快照(例如,在发布之前),请使用lock命令。 这是确定性和可重复构建的关键: pipenv lock --pre

删除虚拟环境

Pipenv很棒,但是您可能会不时清理一些虚拟环境。 就像pipenv --rm一样简单。

安全

Pipfile.lock充分利用了pip的一些重大安全改进。 默认情况下,将使用每个下载包的sha256哈希值生成Pipfile.lock。 这将使pip可以保证您在受到威胁的网络上安装所需的组件,或从不受信任的PyPI端点下载依赖项。

此外,Pipenv提供了check命令,该命令检查是否符合PEP 508-Python软件包的依赖关系规范以及软件包安全性:

~/git/testpipenv > pipenv check .
Checking PEP 508 requirements…
Passed!
Checking installed package safety…
All good!

结论

Pipenv最终将Python封装带到了现代软件开发的最前沿。 它从其他成功的依赖管理系统(例如Rust的Cargo和Javascript的Yarn)中获得启发。

它结合了虚拟环境和程序包管理,并通过优美多彩的信息性消息和隐含的最佳实践提供了卓越的体验! 我强烈建议您开始使用Pipenv来管理Python项目。

此外,不要犹豫,看看我们在Envato市场上有哪些可供出售和研究的物品 ,也不要犹豫,使用下面的提要来问任何问题并提供宝贵的反馈意见。

翻译自: https://code.tutsplus.com/tutorials/revisiting-python-packaging-with-pipenv--cms-30297

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值