跳转到主要内容

检查requirements.txt文件与您的环境之间的差异。

项目描述

https://img.shields.io/github/actions/workflow/status/adamchainz/pip-lock/main.yml?branch=main&style=for-the-badge https://img.shields.io/pypi/v/pip-lock.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

检查requirements.txt文件与当前环境之间的差异。

安装

使用以下命令安装:python -m pip install pip-lock

支持Python 3.8到3.12。


正在处理Django项目? 查阅我的书籍提升您的Django开发体验,其中涵盖了多种提高您开发体验的方法。


示例用法

在应用程序启动时调用 pip_lock.check_requirements() 以验证当前虚拟环境是否符合您的需求文件。这为更改分支等开发人员提供即时反馈,否则他们可能会由于需求不一致而遇到意外的行为或错误。

在Django项目中,将检查添加到 manage.py 文件中是有意义的,这是项目的主要入口点。您可以在导入Django之后添加对 pip_lock.check_requirements() 的调用。例如

#!/usr/bin/env python
import os
import sys
from pathlib import Path


def main():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    try:
        import pip_lock
    except ImportError:
        raise ImportError(
            "Couldn't import pip-lock. Are you on the right virtualenv and up "
            + "to date?"
        )

    requirements_path = str(Path(__file__).parent / "requirements.txt")
    pip_lock.check_requirements(
        requirements_path,
        post_text="\nRun the following:\n\npython -m pip install -r requirements.txt\n",
    )

    execute_from_command_line(sys.argv)


if __name__ == "__main__":
    main()

API

check_requirements(requirements_file_path: str, post_text: str='')) -> None

如果环境与需求文件之间存在不匹配,则使用退出代码1退出并输出到stderr。

requirements_file_pathrequirements.txt 文件的路径 - 我们建议使用绝对文件路径。

post_text 是可选文本,它显示在stderr消息之后。这可以用来显示如何更新需求的说明。

示例

check_requirements(
    "requirements.txt",
    post_text="\nRun the following on your host machine: \n\n    vagrant provision\n",
)
There are requirement mismatches with requirements.txt:
    * Package Django has version 1.9.10 but you have version 1.9.0 installed.
    * Package requests has version 2.11.1 but you have version 2.11.0 installed.
    * Package requests-oauthlib is in requirements.txt but not in virtualenv

Run the following on your host machine:

    vagrant provision

get_mismatches(requirements_file_path: str) -> dict[str, tuple[str, str | None]]

返回一个包含不匹配包的包名到 (预期版本,实际版本) 的字典。

requirements_file_pathrequirements.txt 文件的路径 - 我们建议使用绝对文件路径。

示例

>>> get_mismatches("requirements.txt")
{'django': ('1.10.2', '1.9.0'), 'requests': ('2.11.1', '2.9.2'), 'request-oauthlib': ('0.7.0', None)}

由以下支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面