我有一个requirements.txt
与所需要的我的虚拟环境中的软件包列表文件。 是否有可能找出该文件中提到的所有包是否存在。 如果一些包丢失了,如何找出哪些是缺少的包?
Answer 1:
这样做的Python的方式是通过pkg_resources
API 。 这些要求都写在由setuptools的理解的格式。 例如:
Werkzeug>=0.6.1
Flask
Django>=1.3
示例代码:
import pkg_resources
from pkg_resources import DistributionNotFound, VersionConflict
# dependencies can be any iterable with strings,
# e.g. file line-by-line iterator
dependencies = [
'Werkzeug>=0.6.1',
'Flask>=0.9',
]
# here, if a dependency is not met, a DistributionNotFound or VersionConflict
# exception is thrown.
pkg_resources.require(dependencies)
Answer 2:
您可以运行pip freeze
,看你已经安装了什么,并将它与您的requirements.txt
文件。
如果你想安装缺少的模块,可以运行pip install -r requirements.txt
,这将安装缺少的模块和哪些人失踪并安装在最终告诉你。
Answer 3:
基于由Zaur答案 ,假设你确实使用requirements.txt
文件,你可能需要一个单元测试,也许在tests/test_requirements.py
,即确认包的可用性。
这种方法使用一个子测试独立确认每一个需求。 这是有用的,这样所有的失败都记录在案。
from pathlib import Path
import unittest
import pkg_resources
class TestRequirements(unittest.TestCase):
def test_requirements(self):
"""Recursively confirm that requirements are available."""
# Ref: https://stackoverflow.com/a/45474387/
requirements = (Path(__file__).parents[1] / 'requirements.in').read_text().strip().split('\n')
requirements = [r.strip() for r in requirements]
requirements = [r for r in sorted(requirements) if r and not r.startswith('#')]
for requirement in requirements:
with self.subTest(requirement=requirement):
pkg_resources.require(requirement)
Answer 4:
您可以创建一个与virtualenv中访问系统的网站打包并测试检查包装(或其他依赖关系)是否安装与否。 这样的包是不是真的安装(如果你只是想检查)。 用一个例子的virtualenv包装将是:
$ cat requirements.txt
requests
simplejson
$ mkvirtualenv --system-site-packages test
Running virtualenv with interpreter /usr/bin/python2
New python executable in test/bin/python2
Also creating executable in test/bin/python
Installing setuptools, pip...done.
$ pip install -r requirements.txt
Downloading/unpacking requests (from -r requirements.txt (line 1))
Downloading requests-2.10.0-py2.py3-none-any.whl (506kB): 506kB downloaded
Requirement already satisfied (use --upgrade to upgrade): simplejson in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 2))
Installing collected packages: requests
Successfully installed requests
Cleaning up...
$ pip install -r requirements.txt
Requirement already satisfied (use --upgrade to upgrade): requests in /home/yucer/.virtualenvs/test/lib/python2.7/site-packages (from -r requirements.txt (line 1))
Requirement already satisfied (use --upgrade to upgrade): simplejson in /usr/lib/python2.7/dist-packages (from -r requirements.txt (line 2))
Cleaning up...
$ deactivate
$ rmvirtualenv test
Removing test...
Answer 5:
如果requirements.txt是这样的:
django
oursql
sys
notexistingmodule
然后下面的脚本会告诉你哪些模块丢失:
#!/usr/bin/python3
fname = 'requirements.txt'
with open(fname, 'r', encoding='utf-8') as fhd:
for line in fhd:
try:
exec("import " + line)
except:
print("[ERROR] Missing module:", line)
这将打印:
[ERROR] Missing module: notexistingmodule
文章来源: Check if my Python has all required packages