Pregunta

I wanted to mix a config.py approach and ConfigParser to set some default values in config.py which could be overridden by the user in its root folder:

import ConfigParser
import os

CACHE_FOLDER = 'cache'
CSV_FOLDER = 'csv'

def main():
    cp = ConfigParser.ConfigParser()
    cp.readfp(open('defaults.cfg'))
    cp.read(os.path.expanduser('~/.python-tools.cfg'))
    CACHE_FOLDER = cp.get('folders', 'cache_folder')
    CSV_FOLDER = cp.get('folders', 'csv_folder')

if __name__ == '__main__':
    main()

When running this module I can see the value of CACHE_FOLDER being changed. However when in another module I do the following:

import config

def main()
    print config.CACHE_FOLDER

This will print the original value of the variable ('cache').

Am I doing something wrong ?

¿Fue útil?

Solución

The main function in the code you show only gets run when that module is run as a script (due to the if __name__ == '__main__' block). If you want that turn run any time the module is loaded, you should get rid of that restriction. If there's extra code that actually does something useful in the main function, in addition to setting up the configuration, you might want to split that part out from the setup code:

def setup():
    # the configuration stuff from main in the question

def main():
    # other stuff to be done when run as a script

setup()  # called unconditionally, so it will run if you import this module

if __name__ == "__main__":
    main()  # this is called only when the module is run as a script
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top