Python - Get path of root project structure

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

    You can do this how Django does it: define a variable to the Project Root from a file that is in the top-level of the project. For example, if this is what your project structure looks like:

    project/
        configuration.conf
        definitions.py
        main.py
        utils.py
    

    In definitions.py you can define (this requires import os):

    ROOT_DIR = os.path.dirname(os.path.abspath(__file__)) # This is your Project Root
    

    Thus, with the Project Root known, you can create a variable that points to the location of the configuration (this can be defined anywhere, but a logical place would be to put it in a location where constants are defined - e.g. definitions.py):

    CONFIG_PATH = os.path.join(ROOT_DIR, 'configuration.conf')  # requires `import os`
    

    Then, you can easily access the constant (in any of the other files) with the import statement (e.g. in utils.py): from definitions import CONFIG_PATH.

    0 讨论(0)
  • 2020-12-04 08:45

    Below Code Returns the path until your project root

    import sys
    print(sys.path[1])
    
    0 讨论(0)
  • 2020-12-04 08:45

    This worked for me using a standard PyCharm project with my virtual environment (venv) under the project root directory.

    Code below isnt the prettiest, but consistently gets the project root. It returns the full directory path to venv from the VIRTUAL_ENV environment variable e.g. /Users/NAME/documents/PROJECT/venv

    It then splits the path at the last /, giving an array with two elements. The first element will be the project path e.g. /Users/NAME/documents/PROJECT

    import os
    
    print(os.path.split(os.environ['VIRTUAL_ENV'])[0])
    
    0 讨论(0)
  • 2020-12-04 08:46

    There are many answers here but I couldn't find something simple that covers all cases so allow me to suggest my solution too:

    import pathlib
    import os
    
    def get_project_root():
        """
        There is no way in python to get project root. This function uses a trick.
        We know that the function that is currently running is in the project.
        We know that the root project path is in the list of PYTHONPATH
        look for any path in PYTHONPATH list that is contained in this function's path
        Lastly we filter and take the shortest path because we are looking for the root.
        :return: path to project root
        """
        apth = str(pathlib.Path().absolute())
        ppth = os.environ['PYTHONPATH'].split(':')
        matches = [x for x in ppth if x in apth]
        project_root = min(matches, key=len)
        return project_root

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