Python - Get path of root project structure

后端 未结 16 1837
陌清茗
陌清茗 2020-12-04 08:03

I\'ve got a python project with a configuration file in the project root. The configuration file needs to be accessed in a few different files throughout the project.

16条回答
  •  甜味超标
    2020-12-04 08:37

    A standard way to achieve this would be to use the pkg_resources module which is part of the setuptools package. setuptools is used to create an install-able python package.

    You can use pkg_resources to return the contents of your desired file as a string and you can use pkg_resources to get the actual path of the desired file on your system.

    Let's say that you have a package called stackoverflow.

    stackoverflow/
    |-- app
    |   `-- __init__.py
    `-- resources
        |-- bands
        |   |-- Dream\ Theater
        |   |-- __init__.py
        |   |-- King's\ X
        |   |-- Megadeth
        |   `-- Rush
        `-- __init__.py
    
    3 directories, 7 files
    

    Now let's say that you want to access the file Rush from a module app.run. Use pkg_resources.resouces_filename to get the path to Rush and pkg_resources.resource_string to get the contents of Rush; thusly:

    import pkg_resources
    
    if __name__ == "__main__":
        print pkg_resources.resource_filename('resources.bands', 'Rush')
        print pkg_resources.resource_string('resources.bands', 'Rush')
    

    The output:

    /home/sri/workspace/stackoverflow/resources/bands/Rush
    Base: Geddy Lee
    Vocals: Geddy Lee
    Guitar: Alex Lifeson
    Drums: Neil Peart
    

    This works for all packages in your python path. So if you want to know where lxml.etree exists on your system:

    import pkg_resources
    
    if __name__ == "__main__":
        print pkg_resources.resource_filename('lxml', 'etree')
    

    output:

    /usr/lib64/python2.7/site-packages/lxml/etree
    

    The point is that you can use this standard method to access files that are installed on your system (e.g pip install xxx or yum -y install python-xxx) and files that are within the module that you're currently working on.

提交回复
热议问题