944,124 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 10778
  • Python RSS
Aug 10th, 2005
0

sourcing a python config file?

Expand Post »
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
Python Syntax (Toggle Plain Text)
  1. # if you would like to specify the location of you music directory uncomment the following
  2. #music_dir = '/home/shane/location/of/directory'
  3. # if you would like to permantey set the bitrate used please unmcooment the following
  4. #bit_rate = 192
is their a way to direct my script to use the variables set is this file?
Similar Threads
Reputation Points: 10
Solved Threads: 17
Posting Whiz in Training
shanenin is offline Offline
217 posts
since May 2005
Aug 10th, 2005
0

Re: sourcing a python config file?

this seems to work. let me know if this is not a good way to do it
Python Syntax (Toggle Plain Text)
  1. config_file = '/etc/pythonriprc.py'
  2. execfile(config_file)
Reputation Points: 10
Solved Threads: 17
Posting Whiz in Training
shanenin is offline Offline
217 posts
since May 2005
Aug 10th, 2005
0

Re: sourcing a python 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:
Python Syntax (Toggle Plain Text)
  1. # Config.cfg - a config file for Config.py
  2. # G-Do, 08/08/2005
  3.  
  4. KEY1 Value1
  5. KEY2 Value:2
  6. KEY_3 C:\PROGRA~1\some-directory\somefile.txt
  7. 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:
Python Syntax (Toggle Plain Text)
  1. import sys, re
  2. # -- Loads a config file, creates and returns a dictionary
  3. def load(filename):
  4. # Try to open a file handle on the config file and read the text
  5. # Possible exception #1 - the file might not be found
  6. # Possible exception #2 - the file might have read-protection
  7. try: configfile = open(filename, "r")
  8. except Exception, e: raise
  9. try: configtext = configfile.read()
  10. except Exception, e: raise
  11. # Compile a pattern that matches our key-value line structure
  12. pattern = re.compile("\\n([\w_]+)[\t ]*([\w: \\\/~.-]+)")
  13. # Find all matches to this pattern in the text of the config file
  14. tuples = re.findall(pattern, configtext)
  15. # Create a new dictionary and fill it: for every tuple (key, value) in
  16. # the 'tuples' list, set ret[key] to value
  17. ret = dict()
  18. for x in tuples: ret[x[0]] = x[1]
  19. # Return the fully-loaded dictionary object
  20. return ret
  21. # -- Main method (diagnostic)
  22. def main(args):
  23. # Set a default filename
  24. filename = "doc\Config.cfg"
  25. # If there is a command-line argument, treat it as a filename
  26. if len(args) > 1: filename = args[1]
  27. # Run the load function and deal with any possible exceptions
  28. try: cfg = load(filename)
  29. except Exception, e:
  30. print "ERROR:", filename+":", e.args[1]
  31. sys.exit(1)
  32. # Print each key-value pair in the dictionary, terminate gracefully
  33. for x in cfg: print x, "\t", cfg[x]
  34. sys.exit(0)
  35. # -- Call main if this program is being invoked from the command-line
  36. if __name__ == "__main__": main(sys.argv)
To use this from another class, you would have to say something like:
Python Syntax (Toggle Plain Text)
  1. import sys, Config
  2. try: cfg = Config.load("my_config_file")
  3. except Exception, e:
  4. print "Too bad, we can't load your file"
  5. sys.exit(1)
  6. # Now we can reference all of our config values like so:
  7. print cfg["SOMEKEY"]
  8. # This prints the value associated with SOMEKEY in your config file
  9. # Be careful not to reference a key that doesn't exist!
Reputation Points: 41
Solved Threads: 31
Junior Poster
G-Do is offline Offline
146 posts
since Jun 2005
Aug 10th, 2005
0

Re: sourcing a python config file?

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.
Reputation Points: 10
Solved Threads: 17
Posting Whiz in Training
shanenin is offline Offline
217 posts
since May 2005
Aug 10th, 2005
0

Re: sourcing a python config file?

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.
Reputation Points: 41
Solved Threads: 31
Junior Poster
G-Do is offline Offline
146 posts
since Jun 2005
Aug 10th, 2005
0

Re: sourcing a python config file?

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.
Reputation Points: 10
Solved Threads: 17
Posting Whiz in Training
shanenin is offline Offline
217 posts
since May 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: New Problem with input output in Tk
Next Thread in Python Forum Timeline: Passing result codes to a batch file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC