unified command line args, environment variables, .conf file settings.

smitty1e smitty1e at gmail.com
Fri May 2 22:16:57 EDT 2008


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 at localhost ~/proj/mddl4/test $ ./inputs.py
{'source_db': '/home/sweet/home.db'}
smitty at localhost ~/proj/mddl4/test $ source_db="test_env" ./inputs.py
{'source_db': 'test_env'}
smitty at localhost ~/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 SafeConfigParser
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_option( "-f"    , "--file"
                 , dest    = "source_db"
                 , help    = "source database"
                 , default = PLACEBO           )
(cl_opts, args)  = parser.parse_args()

config    = SafeConfigParser()
config.read(CONF_FILE)
file_conf = dict(config.items(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



More information about the Python-list mailing list