Just a fun exercise to unify some of the major input methods for a
script into a single dictionary.
Here is the output, given a gr.conf file in the same directory with
the contents stated below:
smitty@localhos t ~/proj/mddl4/test $ ./inputs.py
{'source_db': '/home/sweet/home.db'}
smitty@localhos t ~/proj/mddl4/test $ source_db="test _env" ./inputs.py
{'source_db': 'test_env'}
smitty@localhos t ~/proj/mddl4/test $ ./inputs.py -f "test_cli"
{'source_db': 'test_cli'}
For the file
=========
#!/usr/bin/env python
#Goal: unification of environment variables, command line, and
# configuration file settings.
# The .conf file is the specification.
# Optional environment variables can override.
# Optional command-line inputs trump all.
# Example is a file spec for a source database for an application.
# .conf has a contents like:
#============== =============== ===
# [CONF]
# source_db=/home/sweet/home.db
#TODO:
# 1. Decide (make an option?) to retain the simple dictionary or build
a
# class from the options.
# 2. Allow for multiple .conf locations, trying to be cool like
# xorg.conf
from ConfigParser import SafeConfigParse r
from optparse import OptionParser
import os
CONF = "CONF" #section in .conf file
CONF_FILE = "gr.conf" #name of config file
PLACEBO = "placebo" #mindless default that we don't want
gconf = {} #all your config are belong to here
parser = OptionParser()
parser.add_opti on( "-f" , "--file"
, dest = "source_db"
, help = "source database"
, default = PLACEBO )
(cl_opts, args) = parser.parse_ar gs()
config = SafeConfigParse r()
config.read(CON F_FILE)
file_conf = dict(config.ite ms(CONF))
for k in file_conf:
gconf[k]=file_conf[k]
if os.environ.has_ key(k):
gconf[k] = os.environ[k]
if cl_opts.__dict_ _.has_key(k):
if cl_opts.__dict_ _[k]!=PLACEBO:
gconf[k] = cl_opts.__dict_ _[k]
print gconf