sourcecode

Python 패키지의 종속성을 찾는 방법

codebag 2023. 6. 27. 22:10
반응형

Python 패키지의 종속성을 찾는 방법

Python 패키지의 종속성 목록을 프로그래밍 방식으로 가져올 수 있는 방법은 무엇입니까?

setup.py문서화되어 있지만 Python이나 명령줄에서 쉽게 액세스할 수 있는 방법을 찾을 수 없습니다.

이상적으로는 다음과 같은 것을 찾고 있습니다.

$ pip install somepackage --only-list-deps
kombu>=3.0.8
billiard>=3.3.0.13
boto>=2.26

또는:

>>> import package_deps
>>> package = package_deps.find('somepackage')
>>> print package.dependencies
['kombu>=3.0.8', 'billiard>=3.3.0.13', 'boto>=2.26']

참고로, 저는 패키지를 가져오고 참조된 모든 모듈을 찾는 것을 말하는 것이 아닙니다.이렇게 하면 대부분의 종속 패키지를 찾을 수 있지만 필요한 최소 버전 번호는 찾을 수 없습니다.그것은 setup.py 에만 저장됩니다.

그외도에에 pip show [package name]명어다, 있니습이 .pipdeptree.

그냥 해요

$ pip install pipdeptree

그 다음에 달려라

$ pipdeptree

그리고 그것은 당신에게 당신의 의존성을 트리 형태로 보여줄 것입니다. 예를 들어,

flake8==2.5.0
  - mccabe [required: >=0.2.1,<0.4, installed: 0.3.1]
  - pep8 [required: !=1.6.0,>=1.5.7,!=1.6.1,!=1.6.2, installed: 1.5.7]
  - pyflakes [required: >=0.8.1,<1.1, installed: 1.0.0]
ipdb==0.8
  - ipython [required: >=0.10, installed: 1.1.0]

이 프로젝트는 https://github.com/naiquevin/pipdeptree, 에 있으며 사용 정보도 확인할 수 있습니다.

사용해 보십시오.show.pip예:

$ pip show tornado
---
Name: tornado
Version: 4.1
Location: *****
Requires: certifi, backports.ssl-match-hostname

업데이트(지정된 버전에서 삭제 검색):

from pip._vendor import pkg_resources


_package_name = 'somepackage'
_package = pkg_resources.working_set.by_key[_package_name]

print([str(r) for r in _package.requires()])  # retrieve deps from setup.py

Output: ['kombu>=3.0.8', 
         'billiard>=3.3.0.13', 
         'boto>=2.26']

윈도우즈 시스템에서 검색 및 테스트되는 방법에 대한 간략한 요약:

  1. 합니다: PyPI " json 파일입니다.https://pypi.org/pypi/<package>/<version>/json(#7)

  2. 인확을 합니다./site-packages/<package-version>.dist-info/METADATA(#13, 사전 설치 필요)

  3. pip install --no-install <package>사용되지 않음(#11)

  4. pip install --download <package>사용되지 않음(#12)

  5. pip show <package>(#1, #2, 사전 설치 필요)

  6. 다음을 사용하여 스크립트 작성import pip그리고.pip._vendor.pkg_resources사용되지 않음(#6)

  7. 다음을 사용하여 스크립트 작성import pkg_resourcessetuptools패키지(#4, 사전 설치 필요)

  8. https://libraries.io/ 확인 (#5)

  9. 사용하다pipdeptree패키지(#3, #8, 사전 설치 필요)

  10. 사용하다Johnnydep패키지(#10):대부분의 경우 테스트가 중단됩니다.

  11. conda info [package_name]사용되지 않음(#9)

  12. conda search [package_name] --info

    • 할 수 .vc2015_runtime,python_abi,libflang
    • 이 방법은 빌드 및 채널에 따라 다른 패키지를 나열할 수 있습니다.
      conda search "Django==3.2" --info -c conda-forge
django 3.2 pyhd3eb1b0_0
-----------------------
file name   : django-3.2-pyhd3eb1b0_0.conda
...
timestamp   : 2021-04-06 20:19:41 UTC
dependencies:
  - asgiref
  - psycopg2
  - python
  - pytz
  - sqlparse

django 3.2 pyhd8ed1ab_0
-----------------------
file name   : django-3.2-pyhd8ed1ab_0.tar.bz2
...
timestamp   : 2021-04-07 21:15:25 UTC
dependencies:
  - asgiref >=3.3.2,<4
  - python >=3.6
  - pytz
  - sqlparse >=0.2.2

한 가지 더 주목해야 할 것은 각 방법이 다른 결과를 제공할 수 있다는 것입니다.

를 들면, 들면를예,requests/setup.py 는 . chardet,idna,urllib3,그리고.certifi필수 항목입니다.인 게가다, 여의패들지.pyOpenSSL,cryptography,socks,PySocks,win-inet-pton필요할 수 있습니다.

  • 방법 1과 2는 그것에 동의합니다.
  • 방법 8은 모든 항목을 나열합니다(의존성 탐색 버튼을 누르면 중단됨).
  • 방법 12 그냥 리스트chardet,idna,urllib3,그리고.certifi.
  • 메소드 5와 7은 다음과 같은 경우 종속성을 나열하지 않습니다.requests(는) 설다를을 사용하여 됩니다.pip리눅스 도커에서.
  • 5,및 목록 법 5, 7, 9 및 10 록chardet,idna,urllib3,그리고.certifi한다면requests는 윈도우즈 시스템의 Conda 환경에 설치됩니다.

표준 라이브러리를 통해 제공되는 기능을 제공합니다.importlib.metadata.requires() 3 버전 3.8 이상:

In [1]: from importlib.metadata import requires

In [2]: requires('pytype')
Out[2]:
['attrs (>=21.2.0)',
 'importlab (>=0.6.1)',
 'libcst',
 'ninja (>=1.10.0.post2)',
 'pyyaml (>=3.11)',
 'six',
 'tabulate',
 'toml',
 'typed-ast (>=1.4.3)',
 'dataclasses ; python_version < "3.7"']

이전 Python 버전의 경우 사용할 수 있습니다.Python 문서의 관련 섹션: 배포 요구 사항

반환된 문자열을 구문 분석해야 하는 경우requires()를 사용할 것을 강력히 제안합니다.packaging라이브러리 모듈은 PEP 508의 참조 구현이기 때문입니다.종속성 규격 문자열이 복잡한 예:

In [3]: from packaging.requirements import Requirement

In [4]: spec = 'requests [security,test] (>=2.21.0) ; implementation_name == "cpython"'

In [5]: r = Requirement(spec)

In [6]: r.name
Out[6]: 'requests'

In [7]: r.specifier
Out[7]: <SpecifierSet('>=2.21.0')>

In [8]: r.extras
Out[8]: {'security', 'test'}

In [9]: r.marker
Out[9]: <Marker('implementation_name == "cpython"')>

https://libraries.io/ 을 사용합니다.pip을 사용하여 설치하기 전에 종속성을 탐색하는 것이 좋습니다.

예. Google-cloud-storage를 입력하고 검색하면 라이브러리 페이지(https://libraries.io/rubygems/google-cloud-storage) 를 찾을 수 있습니다.'릴리스'(기본값은 최신 버전)에서 종속성을 탐색할 버전을 선택하십시오. '의존성'에서 종속성 목록과 지원되는 버전을 찾을 수 있습니다.

여기에 있는 꽤 많은 답변은 프로그램에서 사용하기 위해 가져온 pip를 보여줍니다.Pip에 대한 설명서는 이러한 Pip 사용에 대해 강력히 권고합니다.

액세스하는 대신pkg_resources파이프 가져오기를 통해 실제로 가져오기만 하면 됩니다.pkg_resources패키지 메타 정보를 프로그래밍 방식으로 보기를 원하는 모든 사용자에게 연결된 pipdocs에서 제안된 솔루션 중 하나입니다.

import pkg_resources

_package_name = 'yourpackagename'
  
def get_dependencies_with_semver_string():
    package = pkg_resources.working_set.by_key[_package_name]
    return [str(r) for r in package.requires()]

패키지 이름이 정확히 무엇인지 알아내는 데 문제가 있다면,WorkingSet에 의해 반환된 인스턴스pkg_resources.working_set도구들__iter__그래서 당신은 그것들을 모두 인쇄할 수 있고 바라건대 그곳에서 당신의 것을 찾을 수 있습니다 :)

예.

import pkg_resources

def print_all_in_working_set():
    ws = pkg_resources.working_set
    for package_metadata in ws:
        print(package_metadata)

이것은 python 2와 3 모두에서 작동합니다(python 2의 인쇄문을 조정해야 합니다).

조니뎁이라는 멋진 도구가 있습니다.검사할 패키지를 설치할 필요가 없다는 장점이 있습니다.

pip install johnnydep

다음과 같이 사용:

johnnydep deepspeech-tflite

(이 답변은 기존 답변이므로 최신 PIP 버전에서는 피해야 하며 이전 PIP 버전을 참조할 수 있도록 여기에 남겨 두어야 합니다.) Alex의 답변은 좋습니다(+1).파이썬에서:

pip._vendor.pkg_resources.working_set.by_key['twisted'].requires()

다음과 같은 것을 반환해야 합니다.

[Requirement.parse('zope.interface>=3.6.0')]

여기서 twisted는 사전에서 찾을 수 있는 패키지 이름입니다.

pip._vendor.pkg_resources.WorkingSet().entry_keys

모든 항목을 나열합니다.

dict = pip._vendor.pkg_resources.WorkingSet().entry_keys
for key in dict:
    for name in dict[key]:
        req =pip._vendor.pkg_resources.working_set.by_key[name].requires()
        print('pkg {} from {} requires {}'.format(name,
                                                  key,
                                                  req))

다음과 같은 목록을 제공해야 합니다.

pkg pyobjc-framework-syncservices from /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC requires [Requirement.parse('pyobjc-core>=2.5.1'), Requirement.parse('pyobjc-framework-Cocoa>=2.5.1'), Requirement.parse('pyobjc-framework-CoreData>=2.5.1')]

파이썬의 이 기사에 따라 이것을 시도해 보십시오.

import pip 
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages]) 
print(installed_packages_list)

다음과 같이 표시됩니다.

['behave==1.2.4', 'enum34==1.0', 'flask==0.10.1', 'itsdangerous==0.24', 
 'jinja2==2.7.2', 'jsonschema==2.3.0', 'markupsafe==0.23', 'nose==1.3.3', 
 'parse-type==0.3.4', 'parse==1.6.4', 'prettytable==0.7.2', 'requests==2.3.0',
 'six==1.6.1', 'vioozer-metadata==0.1', 'vioozer-users-server==0.1', 
 'werkzeug==0.9.4']

쉬운 방법이 있는 것 같습니다.

pip install --dry-run somepackage

저는 조니뎁을 사용해요.

% pipx install johnnydep
% johnnydep channels==2.4.0                                                                                                                                                     
2023-01-25 16:24:25 [info     ] init johnnydist                [johnnydep.lib] dist=channels==2.4.0 parent=None
2023-01-25 16:24:26 [info     ] init johnnydist                [johnnydep.lib] dist=Django>=2.2 parent=channels==2.4.0
2023-01-25 16:24:27 [info     ] init johnnydist                [johnnydep.lib] dist=asgiref~=3.2 parent=channels==2.4.0
2023-01-25 16:24:28 [info     ] init johnnydist                [johnnydep.lib] dist=daphne~=2.3 parent=channels==2.4.0
2023-01-25 16:24:28 [info     ] init johnnydist                [johnnydep.lib] dist=asgiref<4,>=3.5.2 parent=Django>=2.2
2023-01-25 16:24:28 [info     ] init johnnydist                [johnnydep.lib] dist=sqlparse>=0.2.2 parent=Django>=2.2
2023-01-25 16:24:29 [info     ] init johnnydist                [johnnydep.lib] dist=asgiref~=3.2 parent=daphne~=2.3                          
2023-01-25 16:24:29 [info     ] init johnnydist       
...
name                                      summary
----------------------------------------  ---------------------------------------------------------------------------------------------------
channels==2.4.0                           Brings async, event-driven capabilities to Django. Django 2.2 and up only.
├── Django>=2.2                           A high-level Python web framework that encourages rapid development and clean, pragmatic design.
│   ├── asgiref<4,>=3.5.2                 ASGI specs, helper code, and adapters
│   └── sqlparse>=0.2.2                   A non-validating SQL parser.
├── asgiref~=3.2                          ASGI specs, helper code, and adapters
└── daphne~=2.3                           Django ASGI (HTTP/WebSocket) server
    ├── asgiref~=3.2                      ASGI specs, helper code, and adapters
    ├── autobahn>=0.18                    WebSocket client & server library, WAMP real-time framework
    │   ├── cryptography>=3.4.6           cryptography is a package which provides cryptographic recipes and primitives to Python developers.
    │   │   └── cffi>=1.12                Foreign Function Interface for Python calling C code.
    │   │       └── pycparser             C parser in Python
    │   ├── hyperlink>=21.0.0             A featureful, immutable, and correct URL for Python.
    │   │   └── idna>=2.5                 Internationalized Domain Names in Applications (IDNA)
    │   ├── setuptools                    Easily download, build, install, upgrade, and uninstall Python packages
    │   └── txaio>=21.2.1                 Compatibility API between asyncio/Twisted/Trollius
    └── twisted[tls]>=18.7                An asynchronous networking framework written in Python
        ├── Automat>=0.8.0                Self-service finite-state machines for the programmer on the go.
        │   ├── attrs>=19.2.0             Classes Without Boilerplate
        │   └── six                       Python 2 and 3 compatibility utilities
        ├── attrs>=19.2.0                 Classes Without Boilerplate
        ├── constantly>=15.1              Symbolic constants in Python
        ├── hyperlink>=17.1.1             A featureful, immutable, and correct URL for Python.
        │   └── idna>=2.5                 Internationalized Domain Names in Applications (IDNA)
        ├── idna>=2.4                     Internationalized Domain Names in Applications (IDNA)

언급URL : https://stackoverflow.com/questions/29751572/how-to-find-a-python-packages-dependencies

반응형