How do I get the current 'package' name? (setup.py)

后端 未结 2 1813
故里飘歌
故里飘歌 2020-12-19 08:35

How do I get the current topmost package, i.e., the name defined in setup.py?

Here is my tree:

.
|-- README.md
|-- the_project_name_for_         


        
2条回答
  •  执笔经年
    2020-12-19 09:21

    Not entirely sure what the larger goal is, but maybe you could be interested in reading about importlib.resources as well as importlib.metadata.

    Something like the following:

    import importlib.metadata
    import importlib.resources
    
    version = importlib.metadata.version('SomeProject')
    data = importlib.resources.files('top_level_package.sub_package').joinpath('file.txt').read_text()
    

    And more generally, it is near impossible (or not worth the amount of work) to 100% reliably detect the name of the project (SomeProject) from within the code. It is easier to just hard-code it.

    Nevertheless here are some techniques, and ideas to retrieve the name of the project from one of its modules:

    • https://bitbucket.org/pypa/distlib/issues/102/getting-the-distribution-that-a-module
    • https://stackoverflow.com/a/22845276/11138259
    • https://stackoverflow.com/a/56032725/11138259

    Update:

    I believe some function like the following should return the name of the installed distribution containing the current file:

    import pathlib
    import importlib_metadata
    
    def get_project_name():
        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.metadata['Name']
        return None
    

提交回复
热议问题