如何使用pip命令从requirements.txt文件升级我所有的python包?

尝试以下命令

$ pip install --upgrade -r requirements.txt

因为python包的后缀是版本号(Django==1.5.1),所以它们似乎不会升级。有没有比手动编辑requirements.txt文件更好的方法?

EDIT

正如Andy在他的回答中提到的,包被固定到特定的版本,因此不可能通过pip命令升级包。

但是,我们可以使用以下命令使用pip-tools实现这一点。

$ pip-review --auto

这将自动升级requirements.txt中的所有包(确保使用PIP install命令安装PIP -tools)。


当前回答

另一个解决方案是使用升级需求包

pip install upgrade-requirements

然后运行:

upgrade-requirements

它将升级所有不是最新版本的包,并在最后创建一个更新后的requirements.txt。

其他回答

如果你在django项目中安装了任何东西,并且在安装后你想要更新你的需求文件,这个命令可以更新你的需求文件 PIP freeze > requirements.txt

如果你的需求文件在你的项目中不存在,你可以使用这个命令来创建新的需求文件 PIP freeze > requirements.txt

更健壮的解决方案是IMO使用依赖项管理,例如poetry, https://python-poetry.org,它带有详尽的依赖项解析器。

我编辑requirements.txt,如下所示,然后运行$sh ./requirements.txt

pip install -U amqp;
pip install -U appdirs;
pip install -U arrow;
pip install -U Babel;
pip install -U billiard;
pip install -U celery;
pip install -U Django;
pip install -U django-cors-headers;
pip install -U django-crispy-forms;
pip install -U django-filter;
pip install -U django-markdown-deux;
pip install -U django-pagedown;
pip install -U django-timezone-field;
pip install -U djangorestframework;
pip install -U fcm-django;
pip install -U flower;
pip install -U gunicorn;
pip install -U kombu;
pip install -U Markdown;
pip install -U markdown2;
pip install -U packaging;

第二个答案是最有用的,但我想做的是锁定一些包,而其他包在最新版本(例如youtube-dl)。

一个requirements.txt的例子是这样的(~表示兼容):

Pillow==6.2.2
requests~=2.22.0
youtube_dl

然后在终端中,使用命令pip install——upgrade -r requirements.txt

这确保枕头将保持在6.2.2,请求将升级到最新的2.22。X(如果可用),如果还没有安装最新版本的youtube-dl,则将安装。

因为我不能用bash来做这个,我写了一个python模块来创建一个新的没有版本的需求文件并使用它:

data = open('requirements-prod.pip', 'r')
data2 = open('requirements-prod-no-version.pip', 'w')
for line in data.readlines():
    new_line = line[:line.index('==')]
    data2.write(new_line + '\n')
data2.flush()

然后从新文件pip install -U -r requirements-prod-no-version.pip中安装这些库

最后将版本冻结到原始文件pip freeze > requirements-prod.pip