I wrote simple python program that rips, encodes, and gets song data from the cddb. I would like to give the user the option of customizing it to there taste. So I want to make a config file that I can store in /etc(linux fiel location). for example it would look like this

config file

# if you would like to specify the location of you music directory uncomment the following
#music_dir = '/home/shane/location/of/directory'
# if you would like to permantey set the bitrate used please unmcooment the following
#bit_rate = 192

is their a way to direct my script to use the variables set is this file?

this seems to work. let me know if this is not a good way to do it

config_file = '/etc/pythonriprc.py'
execfile(config_file)

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!

thanks you for the nice idea(or even the code to use if that is ok).

back to my simplistic way, so long as my config file is owned by root, wouldn't and hacker need root access to change it. If they had root access my system would already be insecure.

Hmm. Do you intend to make your program available to non-root users? If so, how will a user without root privileges be able to edit his or her own config file? If you don't intend to make the program available to non-root users, then your way works, but I consider that a pretty serious limitation!

And of course, it might not matter now, but someday you might find yourself writing a user-configurable program for a system with multiple users. What will you do then? You certainly can't give them all root privileges! And you shouldn't force them to adopt your configuration settings if those settings aren't relevant to system security and stability.

Plus, there's that whole Unix philosophy thing about how root is only supposed to be invoked to do administrative duties - burning and ripping CDs is only an "administrative duty" in the most liberal sense of the term. :cheesy:

Now, if a possible configuration makes the program do something which would threaten the system, your solution is not only justified, it is necessary. So there's that, too.

Just my $0.02.

EDIT: Absolutely, you can use my code.

I guess I was invisioning this program appealing to users of linux, who are almost always their own admins. They will need root privedges to install the script and modules, they also will need the same privledges to edit the config file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.