如何从中读取依赖项需要.txt一个Python软件包

2024-04-25 07:20:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要依赖关系,因为我想把这些添加到我的RPM元数据中。在

要构建,我使用:

python setup.py bdist_rpm

当我构建包cryptography-2.2.2时,它会创建一个文件/src/cryptography.egg-info/requires.txt

它包含:

^{pr2}$

如何读取所有依赖项,计算[]之间的表达式?在

我在用Python2.7(别问)

我需要以下输出:

idna>=2.1
asn1crypto>=0.21.0
six>=1.4.1
cffi>=1.7
enum34
ipaddress

我想省略其他部分,比如[doc][test]等等。在


Tags: 文件数据pyinfosrctxt关系egg
3条回答

requires.txtdependency metadata的一部分,因此您可以使用easy_install在安装egg时使用的相同工具。假设文件requires.txt在当前目录中:

In [1]: from pkg_resources import Distribution, PathMetadata

In [2]: dist = Distribution(metadata=PathMetadata('.', '.'))

现在您可以使用Distribution.requires()过滤当前平台的所有依赖项:

^{pr2}$

如果我使用Python 2.7,列表会有所不同:

In [4]: sys.version
Out[4]: '2.7.10 (default, Oct  6 2017, 22:29:07) \n[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.31)]'

In [5]: dist.requires()
Out[5]:
[Requirement.parse('idna>=2.1'),
 Requirement.parse('asn1crypto>=0.21.0'),
 Requirement.parse('six>=1.4.1'),
 Requirement.parse('cffi!=1.11.3,>=1.7'),
 Requirement.parse('cffi>=1.7'),
 Requirement.parse('enum34'),
 Requirement.parse('ipaddress')]

或PyPy:

In [2]: sys.version
Out[2]: '3.5.3 (fdd60ed87e941677e8ea11acf9f1819466521bf2, Apr 26 2018, 01:25:35)\n[PyPy 6.0.0 with GCC 4.2.1 Compatible Apple LLVM 9.1.0 (clang-902.0.39.1)]'

In [3]: d.requires()
Out[3]:
[Requirement.parse('idna>=2.1'),
 Requirement.parse('asn1crypto>=0.21.0'),
 Requirement.parse('six>=1.4.1'),
 Requirement.parse('cffi!=1.11.3,>=1.7')]

现在,如果您想生成一个需求字符串列表(比如您想为pip生成一个需求文件),请将需求转换为字符串:

In [8]: os.linesep.join(str(r) for r in dist.requires())
Out[8]:
'idna>=2.1\nasn1crypto>=0.21.0\nsix>=1.4.1\ncffi!=1.11.3,>=1.7'

PEP 508

如果您还想独立于当前平台考虑PEP 508 environment markers,那么事情可能会变得更棘手,但仍然是可管理的。首先,用env标记转换需求:

In [22]: dep_map_pep508 = {k: v for k, v in dist._build_dep_map().items() if k and k.startswith(':')}

In [24]: reqs_pep508 = [str(r) + ';' + k.lstrip(':') for k, v in dep_map_pep508.items() for r in v]

In [25]: reqs_pep508
Out[25]:
["cffi>=1.7;platform_python_implementation != 'PyPy'",
 "enum34;python_version >= '3'",
 "ipaddress;python_version >= '3'"]

现在处理独立于平台的dep,None键下的dist依赖关系图:

In [26]: reqs_no_platform = [str(r) for r in dist._build_dep_map()[None]]

In [27]: reqs_no_platform
Out[27]: ['idna>=2.1', 'asn1crypto>=0.21.0', 'six>=1.4.1', 'cffi!=1.11.3,>=1.7']

将两个列表合并为一个字符串,准备写入需求文件:

In [28]: os.linesep.join(reqs_no_platform + reqs_pep508)
Out[28]: "idna>=2.1\nasn1crypto>=0.21.0\nsix>=1.4.1\ncffi!=1.11.3,>=1.7\ncffi>=1.7;platform_python_implementation != 'PyPy'\nenum34;python_version >= '3'\nipaddress;python_version >= '3'"

所以我找到了一个可行的解决方案,可能还有其他的可能性,但我认为这应该适用于大多数版本

import pkg_resources

lines = open("requirements.txt").readlines()

load_packages = True
for line in lines:
    if line.strip().startswith("#"):
        continue

    if line.startswith("[:"):
        # this is marker, let's evaluate
        load_packages = pkg_resources.evaluate_marker(line.strip()[2:-1])
        continue
    elif line.startswith("["):
        # this is a subsection ignore it
        load_packages = False

    if load_packages and line.strip():
        print(line.strip())

其输出如下

^{pr2}$

如果我改变requirements.txt如下

idna>=2.1
asn1crypto>=0.21.0
six>=1.4.1

[:platform_python_implementation == 'PyPy']
cffi>=1.7

[:python_version > '3']
enum34
ipaddress

输出变为

idna>=2.1
asn1crypto>=0.21.0
six>=1.4.1

您可以测试每行的开头是否与pip依赖关系声明格式匹配。在

Regex可能是模式匹配的最佳解决方案:

pattern = r'^[\w\d_-]+'

其中:

  • ^匹配到行/文件的开头
  • [\w\d_-]+多次匹配任何单词(\w)、数字(\d)、下划线(_)和短划线(-)匹配。在

总而言之:

^{pr2}$

结果:

$ python2.7 test.py
idna>=2.1
asn1crypto>=0.21.0
six>=1.4.1
cffi>=1.7
enum34
ipaddress

相关问题 更多 >