Getting Python package distribution version from within a package

后端 未结 3 1177
灰色年华
灰色年华 2021-01-05 23:53

You can get the version of a python distribution using

import pkg_resources
pkg_resources.get_distribution(\"distro\").version

This is grea

3条回答
  •  执念已碎
    2021-01-06 00:26

    I believe the project's name should be hard-coded if possible. If not then some function like the following could help figuring out the metadata for the installed distribution containing the current file (__file__):

    import pathlib
    import importlib_metadata
    
    def get_project_distribution():
        for dist in importlib_metadata.distributions():
            try:
                relative = pathlib.Path(__file__).relative_to(dist.locate_file(''))
            except ValueError:
                pass
            else:
                if relative in dist.files:
                    return dist
        return None
    
    project_distribution = get_project_distribution()
    if project_distribution:
        project_name = project_distribution.metadata['Name']
        version = project_distribution.metadata['Version']
    

提交回复
热议问题