Hi shanenin,
You might want to check out the ConfigParser object . I don't use it myself; I wrote my own.
I must confess: I'm a little leery of your solution, since it involves executing the contents of a file without making security checks first. What if the file gets hacked? :eek:
Here's what I do:
My config files contain three kinds of lines: comments, blank lines, and key-value lines. Comment lines begin with a pound sign (#), blank lines are just blank, and key-value lines are a key (letters, numbers, and underscores only) followed by one or more tabs and/or spaces, followed by a value (can contain letters, numbers, spaces, or any of /:\~.-).
Here's a sample config file that conforms to the stated rules:
# Config.cfg - a config file for Config.py
# G-Do, 08/08/2005
KEY1 Value1
KEY2 Value:2
KEY_3 C:\PROGRA~1\some-directory\somefile.txt
KEY_4 http://www.google.com/~g-do My Config class includes a config file-loading function which accepts a config file's name as input and returns a dictionary with the keys and values from the file already loaded. It also has a diagnostic main method that loads either the dummy config file above, or a config file the user specifies on the command line, then prints the keys and values. The code looks like:
import sys, re
# -- Loads a config file, creates and returns a dictionary
def load(filename):
# Try to open a file handle on the config file and read the text
# Possible exception #1 - the file might not be found
# Possible exception #2 - the file might have read-protection
try: configfile = open(filename, "r")
except Exception, e: raise
try: configtext = configfile.read()
except Exception, e: raise
# Compile a pattern that matches our key-value line structure
pattern = re.compile("\\n([\w_]+)[\t ]*([\w: \\\/~.-]+)")
# Find all matches to this pattern in the text of the config file
tuples = re.findall(pattern, configtext)
# Create a new dictionary and fill it: for every tuple (key, value) in
# the 'tuples' list, set ret[key] to value
ret = dict()
for x in tuples: ret[x[0]] = x[1]
# Return the fully-loaded dictionary object
return ret
# -- Main method (diagnostic)
def main(args):
# Set a default filename
filename = "doc\Config.cfg"
# If there is a command-line argument, treat it as a filename
if len(args) > 1: filename = args[1]
# Run the load function and deal with any possible exceptions
try: cfg = load(filename)
except Exception, e:
print "ERROR:", filename+":", e.args[1]
sys.exit(1)
# Print each key-value pair in the dictionary, terminate gracefully
for x in cfg: print x, "\t", cfg[x]
sys.exit(0)
# -- Call main if this program is being invoked from the command-line
if __name__ == "__main__": main(sys.argv) To use this from another class, you would have to say something like:
import sys, Config
try: cfg = Config.load("my_config_file")
except Exception, e:
print "Too bad, we can't load your file"
sys.exit(1)
# Now we can reference all of our config values like so:
print cfg["SOMEKEY"]
# This prints the value associated with SOMEKEY in your config file
# Be careful not to reference a key that doesn't exist!