Program Tip

pip 종속성 / 요구 사항을 나열하는 방법이 있습니까?

programtip 2020. 10. 26. 08:30
반응형

pip 종속성 / 요구 사항을 나열하는 방법이 있습니까?


설치를 거치지 않고 pip install설치할 모든 패키지를 빠르게보고 싶습니다 .


수락 된 답변은 더 이상 최신 버전의 pip와 관련이 없으며 여러 의견을 숙독하지 않고 즉각적인 답변을 제공하지 않으므로 업데이트 된 답변을 제공하고 있습니다.

이것은 pip 버전 8.1.2 , 9.0.1 , 10.0.118.1 에서 테스트되었습니다 .

Linux에서 현재 디렉토리를 어지럽히 지 않고 출력을 얻으려면

pip download [package] -d /tmp --no-binary :all:

-d 다운로드가 파일을 넣어야하는 디렉토리를 pip에 알려줍니다.

더 나은 방법은이 스크립트를 패키지 이름 인 인수와 함께 사용하여 종속성 만 출력으로 가져옵니다.

#!/bin/sh

PACKAGE=$1
pip download $PACKAGE -d /tmp --no-binary :all: \
| grep Collecting \
| cut -d' ' -f2 \
| grep -Ev "$PACKAGE(~|=|\!|>|<|$)"

여기 에서도 사용할 수 있습니다 .


내 프로젝트 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

참고 :이 답변에 사용 된 기능 은 2014 년더 이상 사용되지 않고 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디렉터리 를 제거하는 것만 큼 쉽습니다 .


패키지가 설치되어있는 경우에만 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

명령은 pip install <package> --download <path>@radtek 의해 의견 바와 같이 --no 설치되어 7.0.0 (2015년 5월 21일)의 이후로, 표기 제거 에서 pip. 그러면 필요한 종속성이 <path>.


The answer by @Jmills is stellar. It has a bug in the negative matching which causes some dependencies to be missed. In order to ensure that a package is not marked as a dependency of itself, he included the line grep -v $PACKAGE, which also negatively matches any dependency with the original package name as a sub-string, so jupyter_core is not listed as a dependency of jupyter, for example.

For my use case, I found it useful to have an implementation in python code instead of a shell script. I haven't included the original bug, though anyone is free to add it back in if they would like. I've borrowed an stdout capturing context manager to hopefully make the dependency gathering more intuitive.

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:]

In case you don't need the version numbers, those are easy enough to filter out.

import re

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

I quote an alternative solution from @onnovalkering:

PyPi provides a JSON endpoint with package metadata:

>>> 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.*'

For a specific package version, add an additional version segment to the URL:

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

Also if you are using conda (as suggested by @ShpielMeister), you can use:

conda info package==X.X.X

to display information, including dependencies for a particular version or:

conda info package

to display information, including dependencies about all supported versions of that package.


Another option is to use a helper script similar to this one which uses the pip.req.parse_requirements API to parse requirements.txt files and a distutils.core.setup replacement to parse setup.py files.


IN CASE you have the packages already installed, this script can fetch all the dependencies from a requirements file by running the command pip show mentioned by @Sardathrion.

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

참고URL : https://stackoverflow.com/questions/11147667/is-there-a-way-to-list-pip-dependencies-requirements

반응형