检查我的 Python 是否具有所有必需的包
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16294819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if my Python has all required packages
提问by Alagappan Ramu
I have a requirements.txtfile with a list of packages that are required for my virtual environment. Is it possible to find out whether all the packages mentioned in the file are present. If some packages are missing, how to find out which are the missing packages?
我有一个requirements.txt文件,其中包含我的虚拟环境所需的软件包列表。是否可以找出文件中提到的所有包是否都存在。如果某些软件包丢失,如何找出丢失的软件包?
采纳答案by Zaur Nasibov
UPDATE:
更新:
An up-to-date and improved way to do this is via distutils.text_file.TextFile. See Acumenus' answerbelow for details.
一种最新且改进的方法是通过distutils.text_file.TextFile. 有关详细信息,请参阅下面Acumenus 的回答。
ORIGINAL:
原文:
The pythonic way of doing it is via the pkg_resourcesAPI. The requirements are written in a format understood by setuptools. E.g:
这样做的pythonic方法是通过pkg_resourcesAPI。这些要求是以 setuptools 可以理解的格式编写的。例如:
Werkzeug>=0.6.1
Flask
Django>=1.3
The example code:
示例代码:
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)
回答by John Jiang
You can run pip freezeto see what you have installed and compare it to your requirements.txtfile.
您可以运行pip freeze以查看已安装的内容并将其与您的requirements.txt文件进行比较。
If you want to install missing modules you can run pip install -r requirements.txtand that will install any missing modules and tell you at the end which ones were missing and installed.
如果你想安装缺失的模块,你可以运行pip install -r requirements.txt,这将安装任何缺失的模块,并在最后告诉你哪些缺失并安装了。
回答by Jean Ctheitroadon
If requirements.txt is like :
如果requirements.txt是这样的:
django
oursql
sys
notexistingmodule
Then the following script will tell you which modules are missing :
然后以下脚本将告诉您缺少哪些模块:
#!/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)
This would print :
这将打印:
[ERROR] Missing module: notexistingmodule
回答by yucer
You can create a virtualenv with access to the system site packages and test check whether the package (or another dependencies) are installed or not. This way the packages are not really installed (if you just want to check). An example using virtualenv wrapperwould be:
您可以创建一个可以访问系统站点包的 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...
回答by Acumenus
Based on the answer by Zaur, assuming you indeed use a requirements file, you may want a unit test, perhaps in tests/test_requirements.py, that confirms the availability of packages.
根据Zaur的回答,假设您确实使用了需求文件,您可能需要一个单元测试,可能在 中tests/test_requirements.py,以确认包的可用性。
Moreover, this approach uses a subtestto independently confirm each requirement. This is useful so that all failures are documented. Without subtests, only a single failure is documented.
此外,这种方法使用子测试来独立确认每个需求。这很有用,以便记录所有故障。没有子测试,只记录一个失败。
"""Test availability of required packages."""
import unittest
from pathlib import Path
import pkg_resources
_REQUIREMENTS_PATH = Path(__file__).parent.with_name("requirements.txt")
class TestRequirements(unittest.TestCase):
"""Test availability of required packages."""
def test_requirements(self):
"""Test that each required package is available."""
# Ref: https://stackoverflow.com/a/45474387/
requirements = pkg_resources.parse_requirements(_REQUIREMENTS_PATH.open())
for requirement in requirements:
requirement = str(requirement)
with self.subTest(requirement=requirement):
pkg_resources.require(requirement)
回答by cov
If you're interested in doing this from the command line, pip-missing-reqswill list missing packages. Example:
如果您有兴趣从命令行执行此操作,pip-missing-reqs将列出丢失的包。例子:
$ pip-missing-reqs directory
Missing requirements:
directory/exceptions.py:11 dist=grpcio module=grpc
(pip checkand pipdeptree --warn failonly audit installed packages for compatibility with each other, without checking requirements.txt.)
(pip check并且pipdeptree --warn fail仅审核已安装的软件包以确保彼此的兼容性,而不检查requirements.txt.)
回答by Arkq
In addition to check whether modules listed in requirements.txtare installed, you may want to check whether all used modules by your project are indeed listed in the requirements.txtfile.
除了检查是否requirements.txt安装了列出的模块之外,您可能还想检查您的项目使用的所有模块是否确实在requirements.txt文件中列出。
If you are using flake8 for style-checking, you can add flake8-requirementsplugin for flake8. It will automatically check whether imported modules are available in setup.py, requirements.txtor pyproject.tomlfile. Additionally, for custom modules you can add custom configuration with known-modules (in order to prevent flake8 warnings). For more configuration options, see flake8-requirements project's description.
如果您使用 flake8 进行样式检查,您可以为 flake8添加flake8-requirements插件。它将自动检查导入的模块是否在setup.py、requirements.txt或pyproject.toml文件中可用。此外,对于自定义模块,您可以使用已知模块添加自定义配置(以防止 flake8 警告)。更多配置选项见 flake8-requirements 项目说明。

