Python - Get path of root project structure

后端 未结 16 1830
陌清茗
陌清茗 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:29

    I struggled with this problem too until I came to this solution. This is the cleanest solution in my opinion.

    In your setup.py add "packages"

    setup(
    name='package_name'
    version='0.0.1'
    .
    .
    .
    packages=['package_name']
    .
    .
    .
    )
    

    In your python_script.py

    import pkg_resources
    import os
    
    resource_package = pkg_resources.get_distribution(
        'package_name').location
    config_path = os.path.join(resource_package,'configuration.conf')
    

提交回复
热议问题