什么时候在 setup.py 中使用 pip 需求文件和 install_need?

我使用 pip 和 viralenv 来打包和安装一些 Python 库。

我想我正在做的是一个很常见的情况。我是几个库的维护者,我可以为它们显式地指定依赖项。我的一些库依赖于具有传递依赖关系的第三方库,而我对这些依赖关系没有控制权。

我试图实现的是在我的一个库上的 pip install下载/安装它的所有上游依赖项。我在 pip 文档中纠结的是,如果/如何 要求档案可以自己做到这一点,或者他们真的只是一个使用 install_requires的补充。

我是否会在所有库中使用 install_requires来指定依赖项和版本范围,然后只使用需求文件来解决冲突和/或冻结它们以进行生产构建?

让我们假设我生活在一个虚构的世界(我知道,我知道) ,我对上游的依赖是直截了当的,并且保证不会冲突或打破向下兼容。我是否会被迫使用 pip 需求文件,还是仅仅让 pip/setuptools/distribution 安装基于 install_requires的所有东西?

这里有很多类似的问题,但是我找不到任何一个像什么时候使用一个或者另一个或者两个和谐地一起使用这样基本的问题。

36538 次浏览

My philosophy is that install_requires should indicate a minimum of what you need. It might include version requirements if you know that some versions will not work; but it shouldn't have version requirements where you aren't sure (e.g., you aren't sure if a future release of a dependency will break your library or not).

Requirements files on the other hand should indicate what you know does work, and may include optional dependencies that you recommend. For example you might use SQLAlchemy but suggest MySQL, and so put MySQLdb in the requirements file).

So, in summary: install_requires is to keep people away from things that you know don't work, while requirements files to lead people towards things you know do work. One reason for this is that install_requires requirements are always checked, and cannot be disabled without actually changing the package metadata. So you can't easily try a new combination. Requirements files are only checked at install time.

here's what I put in my setup.py:

# this grabs the requirements from requirements.txt
REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()]


setup(
.....
install_requires=REQUIREMENTS
)

I only ever use a setup.py and install_requires because there is only one place to look at. It is just as powerful as having a requirements file and there is no duplication to maintain.

The Python Packaging User Guide has a page about this topic, I highly recommend you read it:

Summary:

install_requires is there to list the dependencies of the package that absolutely must be installed for the package to work. It is not meant to pin the dependencies to specific versions, but ranges are accepted, for example install_requires=['django>=1.8']. install_requires is observed by pip install name-on-pypi and other tools.

requirements.txt is just a text file, that you can choose to run pip install -r requirements.txt against. It's meant to have versions of all dependencies and subdependencies pinned, like this: django==1.8.1. You can create one using pip freeze > requirements.txt. (Some services, like Heroku, automatically run pip install -r requirements.txt for you.) pip install name-on-pypi does not look at requirements.txt, only at install_requires.