How do you find python package metadata information given a module

前端 未结 1 1408
半阙折子戏
半阙折子戏 2021-01-24 18:10

I\'m trying to retrieve metadata information for a python package given the name of the module.

I can use importlib-metadata to retrieve the information, but in some cas

1条回答
  •  粉色の甜心
    2021-01-24 18:25

    I believe something like the following should work:

    #!/usr/bin/env python3
    
    import importlib.util
    import pathlib
    
    import importlib_metadata
    
    def get_distribution(file_name):
        result = None
        for distribution in importlib_metadata.distributions():
            try:
                relative = (
                    pathlib.Path(file_name)
                    .relative_to(distribution.locate_file(''))
                )
            except ValueError:
                pass
            else:
                if relative in distribution.files:
                    result = distribution
        return result
    
    def alpha():
        file_name = importlib.util.find_spec('easy_install').origin
        distribution = get_distribution(file_name)
        print("alpha", distribution.metadata['Name'])
    
    def bravo():
        file_name = importlib_metadata.__file__
        distribution = get_distribution(file_name)
        print("bravo", distribution.metadata['Name'])
    
    if __name__ == '__main__':
        alpha()
        bravo()
    

    0 讨论(0)
提交回复
热议问题