有没有办法列出pip依赖/需求?

时间:2012-06-21 22:23:10

标签: python pip

如果不进行安装,我想快速查看pip install将要安装的所有软件包。

11 个答案:

答案 0 :(得分:84)

已接受的答案已不再适用于更新的pip版本,如果不仔细阅读多条评论,则无法立即给出答案,因此我提供了更新的答案。

使用点数版本 8.1.2 9.0.1 10.0.1 18.1

要在Linux上使用

而不会使当前目录混乱而获得输出
-d

#!/bin/sh PACKAGE=$1 pip download $PACKAGE -d /tmp --no-binary :all: \ | grep Collecting \ | cut -d' ' -f2 \ | grep -Ev "$PACKAGE(~|=|\!|>|<|$)" 告诉pip下载应放入文件的目录。

更好的是,只需使用此脚本,并将参数作为包名称,仅将依赖项作为输出:

{{1}}

也可用here

答案 1 :(得分:18)

查看我的项目johnnydep

安装:

pip install johnnydep

用法示例:

$ johnnydep requests
name                       summary
-------------------------  ----------------------------------------------------------------------
requests                   Python HTTP for Humans.
├── certifi>=2017.4.17     Python package for providing Mozilla's CA Bundle.
├── chardet<3.1.0,>=3.0.2  Universal encoding detector for Python 2 and 3
├── idna<2.7,>=2.5         Internationalized Domain Names in Applications (IDNA)
└── urllib3<1.23,>=1.21.1  HTTP library with thread-safe connection pooling, file post, and more.

更复杂的树:

$ johnnydep ipython 
name                              summary
--------------------------------  -----------------------------------------------------------------------------
ipython                           IPython: Productive Interactive Computing
├── appnope                       Disable App Nap on OS X 10.9
├── decorator                     Better living through Python with decorators
├── jedi>=0.10                    An autocompletion tool for Python that can be used for text editors.
│   └── parso==0.1.1              A Python Parser
├── pexpect                       Pexpect allows easy control of interactive console applications.
│   └── ptyprocess>=0.5           Run a subprocess in a pseudo terminal
├── pickleshare                   Tiny 'shelve'-like database with concurrency support
├── prompt-toolkit<2.0.0,>=1.0.4  Library for building powerful interactive command lines in Python
│   ├── six>=1.9.0                Python 2 and 3 compatibility utilities
│   └── wcwidth                   Measures number of Terminal column cells of wide-character codes
├── pygments                      Pygments is a syntax highlighting package written in Python.
├── setuptools>=18.5              Easily download, build, install, upgrade, and uninstall Python packages
├── simplegeneric>0.8             Simple generic functions (similar to Python's own len(), pickle.dump(), etc.)
└── traitlets>=4.2                Traitlets Python config system
    ├── decorator                 Better living through Python with decorators
    ├── ipython-genutils          Vestigial utilities from IPython
    └── six                       Python 2 and 3 compatibility utilities

答案 2 :(得分:16)

  

注意:此回答中使用的功能是deprecated in 2014removed in 2015。请参阅适用于现代pip的其他答案。

您可以直接使用pip获得的最接近的是使用--no-install参数:

pip install --no-install <package>

例如,这是安装celery时的输出:

Downloading/unpacking celery                                                                                   
  Downloading celery-2.5.5.tar.gz (945Kb): 945Kb downloaded
  Running setup.py egg_info for package celery

    no previously-included directories found matching 'tests/*.pyc'
    no previously-included directories found matching 'docs/*.pyc'
    no previously-included directories found matching 'contrib/*.pyc'
    no previously-included directories found matching 'celery/*.pyc'
    no previously-included directories found matching 'examples/*.pyc'
    no previously-included directories found matching 'bin/*.pyc'
    no previously-included directories found matching 'docs/.build'
    no previously-included directories found matching 'docs/graffles'
    no previously-included directories found matching '.tox/*'
Downloading/unpacking anyjson>=0.3.1 (from celery)
  Downloading anyjson-0.3.3.tar.gz
  Running setup.py egg_info for package anyjson

Downloading/unpacking kombu>=2.1.8,<2.2.0 (from celery)
  Downloading kombu-2.1.8.tar.gz (273Kb): 273Kb downloaded
  Running setup.py egg_info for package kombu

Downloading/unpacking python-dateutil>=1.5,<2.0 (from celery)
  Downloading python-dateutil-1.5.tar.gz (233Kb): 233Kb downloaded
  Running setup.py egg_info for package python-dateutil

Downloading/unpacking amqplib>=1.0 (from kombu>=2.1.8,<2.2.0->celery)
  Downloading amqplib-1.0.2.tgz (58Kb): 58Kb downloaded
  Running setup.py egg_info for package amqplib

Successfully downloaded celery anyjson kombu python-dateutil amqplib

不可否认,这确实会以临时文件的形式留下一些东西,但它确实实现了目标。如果你使用virtualenv(你应该这样做)这样做,那么清理就像删除<virtualenv root>/build目录一样简单。

答案 3 :(得分:13)

当且仅当包安装时,您可以使用pip show <package>。查找输出结尾处的Requires:字段。显然,这会破坏您的要求,但仍然可能有用。

例如:

$ pip --version
pip 7.1.0 [...]
$ pip show pytest
---
Metadata-Version: 2.0
Name: pytest
Version: 2.7.2
Summary: pytest: simple powerful testing with Python
Home-page: http://pytest.org
Author: Holger Krekel, Benjamin Peterson, Ronny Pfannschmidt, Floris Bruynooghe and others
Author-email: holger at merlinux.eu
License: MIT license
Location: /home/usr/.tox/develop/lib/python2.7/site-packages
Requires: py

答案 4 :(得分:0)

应该使用命令pip install <package> --download <path>,如@radtek的评论中所述,自7.0.0(2015-05-21)起, - no-install removed来自{{} 1}}。这会将所需的依赖项下载到pip

答案 5 :(得分:0)

另一种选择是使用类似于this one的帮助程序脚本,该脚本使用pip.req.parse_requirements API来解析requirements.txt个文件,使用distutils.core.setup替换来解析setup.py文件。

答案 6 :(得分:0)

@Jmills的答案非常出色。它在负匹配中有一个错误,导致错过某些依赖项。为了确保包没有标记为自身的依赖关系,他包含了行grep -v $PACKAGE,其中也与原始包名称作为子字符串的任何依赖项负面匹配,因此,jupyter_core未列为jupyter的依赖项,例如。

对于我的用例,我发现在python代码而不是shell脚本中实现它是有用的。我还没有包含原始的bug,但是如果他们愿意的话,任何人都可以自由添加它。我借用了一个stdout捕获上下文管理器,希望能够使依赖性收集更加直观。

from cStringIO import StringIO
import sys
import pip

class Capturing(list):
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout = self._stringio = StringIO()
        return self
    def __exit__(self, *args):
        self.extend(self._stringio.getvalue().splitlines())
        del self._stringio    # free up some memory
        sys.stdout = self._stdout

def get_dependencies(module_name):
    with Capturing() as out:
        pip.main(['download', module_name, '-d', '/tmp', '--no-binary', ':all:'])
    return [line.split(' ')[1] for line in out if 'Collecting' == line[:10]][1:]

如果您不需要版本号,那么这些版本号很容易过滤掉。

import re

def module_name(module_name_with_version):
    return re.match('[^!<>=]*', module_name_with_version).group()

答案 7 :(得分:0)

使用 pipdeptree ( pip install pipdeptree)。需要安装包。

$ pipdeptree -p pandas
pandas==1.2.2
  - numpy [required: >=1.16.5, installed: 1.19.5]
  - python-dateutil [required: >=2.7.3, installed: 2.8.1]
    - six [required: >=1.5, installed: 1.15.0]
  - pytz [required: >=2017.3, installed: 2021.1]

使用 johnnydep (pip install johnnydep)。较慢,因为它会下载包的轮子。

$ johnnydep pandas
2021-06-09 11:01:21 [info     ] init johnnydist                [johnnydep.lib] dist=pandas parent=None
2021-06-09 11:01:22 [info     ] init johnnydist                [johnnydep.lib] dist=numpy>=1.16.5 parent=pandas
2021-06-09 11:01:22 [info     ] init johnnydist                [johnnydep.lib] dist=python-dateutil>=2.7.3 parent=pandas
2021-06-09 11:01:23 [info     ] init johnnydist                [johnnydep.lib] dist=pytz>=2017.3 parent=pandas
2021-06-09 11:01:23 [info     ] init johnnydist                [johnnydep.lib] dist=six>=1.5 parent=python-dateutil>=2.7.3
name                        summary
--------------------------  -----------------------------------------------------------------------
pandas                      Powerful data structures for data analysis, time series, and statistics
├── numpy>=1.16.5           NumPy is the fundamental package for array computing with Python.
├── python-dateutil>=2.7.3  Extensions to the standard Python datetime module
│   └── six>=1.5            Python 2 and 3 compatibility utilities
└── pytz>=2017.3            World timezone definitions, modern and historical

答案 8 :(得分:0)

我认为这些答案已经过时,现在有更好的解决方案。原帖在这里:

要为 requirements.txtinstall_requires 中的 setup.cfg 中列出的软件包生成 setup.py,您需要安装 pip-tools

pip install pip-tools
pip-compile

要生成包含在 requirements.txt 下为 extras_requirestests 指定的包的 dev 文件:

pip-compile --extra tests --extra devrequirements.txt file with packages listed under

此外,您还可以使用 requirements.in 文件代替 setup.cfgsetup.py 来列出您的要求。

pip-compile requirements.in

答案 9 :(得分:-1)

例如,如果已经安装了软件包,则此脚本可以通过运行@Sardathrion提到的命令pip show从请求文件中获取所有依赖项。

import commands

fil = open("requirements.txt")
for package_line in fil.readlines():
    if "==" in package_line:
        package = package_line.split("==")[0]
    elif "[" in package_line:
        package = package_line.split("[")[0]
    else:
        package = package_line

    output = commands.getoutput('pip show %s' % package)
    try:
        required = output.split("\n")[-1].split(":")[1]
    except Exception as e:
        required = ""
        print "error {} in package {}".format(e, package)

    if len(required) > 1:
        print package, "-- ****%s***" % required

答案 10 :(得分:-1)

我引用了alternative solution from @onnovalkering

  

PyPi为JSON端点提供了包元数据:

>>> import requests
>>> url = 'https://pypi.org/pypi/{}/json'
>>> json = requests.get(url.format('pandas')).json()
>>> json['info']['requires_dist']
['numpy (>=1.9.0)', 'pytz (>=2011k)', 'python-dateutil (>=2.5.0)']
>>> json['info']['requires_python']
'>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*'
     

对于特定的软件包版本,将一个附加的版本段添加到   网址:

https://pypi.org/pypi/pandas/0.22.0/json

此外,如果您使用的是conda(as suggested by @ShpielMeister),则可以使用:

conda info package==X.X.X

显示信息,包括特定版本或以下版本的依赖关系:

conda info package

显示信息,包括有关该软件包所有受支持版本的依赖性。