Python - Get path of root project structure

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

    If you are working with anaconda-project, you can query the PROJECT_ROOT from the environment variable --> os.getenv('PROJECT_ROOT'). This works only if the script is executed via anaconda-project run .

    If you do not want your script run by anaconda-project, you can query the absolute path of the executable binary of the Python interpreter you are using and extract the path string up to the envs directory exclusiv. For example: The python interpreter of my conda env is located at:

    /home/user/project_root/envs/default/bin/python

    # You can first retrieve the env variable PROJECT_DIR.
    # If not set, get the python interpreter location and strip off the string till envs inclusiv...
    
    if os.getenv('PROJECT_DIR'):
        PROJECT_DIR = os.getenv('PROJECT_DIR')
    else:
        PYTHON_PATH = sys.executable
        path_rem = os.path.join('envs', 'default', 'bin', 'python')
        PROJECT_DIR = py_path.split(path_rem)[0]
    

    This works only with conda-project with fixed project structure of a anaconda-project

提交回复
热议问题