Getting Python package distribution version from within a package

后端 未结 3 1196
灰色年华
灰色年华 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:20

    After a couple of hours of exploring pkg_resources and reading the source for pip's uninstall I've got the following working:

    import inspect
    import pkg_resources
    import csv
    
    class App(object):
        def get_app_version(self) -> str:
            # Iterate through all installed packages and try to find one that has the app's file in it
            app_def_path = inspect.getfile(self.__class__)
            for dist in pkg_resources.working_set:
                try:
                    filenames = [
                        os.path.normpath(os.path.join(dist.location, r[0]))
                        for r in csv.reader(dist.get_metadata_lines("RECORD"))
                    ]
                    if app_def_path in filenames:
                        return dist.version
                except FileNotFoundError:
                    # Not pip installed or something
                    pass
            return "development"
    

    This iterates through all installed packages and for each of those iterates through its list of files and tries to match that to the current file, this matches the package to the distribution. It's not really ideal, and I'm still open to better answers.

提交回复
热议问题