Check if my Python has all required packages

后端 未结 7 1870
悲&欢浪女
悲&欢浪女 2020-12-23 09:53

I have a requirements.txt file with a list of packages that are required for my virtual environment. Is it possible to find out whether all the packages mention

7条回答
  •  再見小時候
    2020-12-23 10:40

    UPDATE:

    An up-to-date and improved way to do this is via distutils.text_file.TextFile. See Acumenus' answer below for details.

    ORIGINAL:

    The pythonic way of doing it is via the pkg_resources API. The requirements are written in a format understood by setuptools. E.g:

    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)
    

提交回复
热议问题