Where to put a configuration file in Python?

a 夏天 提交于 2019-11-29 18:56:55

Have you seen how configuration files work? Read up on "rc" files, as they're sometimes called. "bashrc", "vimrc", etc.

There's usually a multi-step search for the configuration file.

  1. Local directory. ./myproject.conf.

  2. User's home directory (~user/myproject.conf)

  3. A standard system-wide directory (/etc/myproject/myproject.conf)

  4. A place named by an environment variable (MYPROJECT_CONF)

The Python installation would be the last place to look.

config= None
for loc in os.curdir, os.path.expanduser("~"), "/etc/myproject", os.environ.get("MYPROJECT_CONF"):
    try: 
        with open(os.path.join(loc,"myproject.conf")) as source:
            config.readfp( source )
    except IOError:
        pass

The appdirs package does a nice job on finding the standard place for installed apps on various platforms. I wonder if extending it to discover or allow some sort of "uninstalled" status for developers would make sense.

If you're using setuptools, see the chapter on using non-package data files. Don't try to look for the files yourself.

Another option is to keep all the .cfg and .ini files in the home directory, like 'boto' does.

import os.path
config_file = os.path.join(os.path.expanduser("~"), '.myproject')

I don't think there is a clean way to deal with that. You could simply choose to test for the existence of the 'local' file, which would work in dev mode. Otherwise, fall back to the production path:

import os.path

main_base = os.path.dirname(__file__)
config_file = os.path.join(main_base, "conf", "myproject.conf")

if not os.path.exists(config_file):
    config_file = PROD_CONFIG_FILE   # this could also be different based on the OS
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!