![]() |
Storing preferences
I want to store my script's preferences in a file that is human-readable and -editable. Is there a standard Python class for storing and parsing a file in the format VARIABLE=VALUE on each line? I know I can write my own function to do this very easily but since Python seems to have built-in classes for just about everything I thought I'd ask. Thanks.
|
Well, it's a little dangerous. But you can actually just straight out execute the configuration file.
:
exec open('options.conf', 'r').read()But, it's dangerous. And slow. :D |
Quote:
As for slow, I'd imagine that loading Python is way faster than reading in XML via Python or parsing stuff yourself. Also, if your config file is just named config.py, you can just import it without having to manually open and read and exec it. :
import configWhen I want simple key=value, newline seperated config options, I just do something like this: :
def readConfig(fname): |
Take a look at ConfigParser.
If you had a configuration file called test.cfg: :
[defaults]Then you could access it thus: :
>>> from ConfigParser import ConfigParser |
Does ConfigParser support comments, eg lines beginning with #?
What I am trying to do is read and set each variable AND value from the config file. At the moment I don't know the names of the variables, which I was asking about in this thread. This probably isn't possible with ConfigParser. |
I was bored so I made this silly little class.
It gets the job done, and it's safe from any stupid stunts the user tries to pull. :
With some simple modifications, you could make it so it sets actual variables in an object using "setattr". That's if you would rather not have a dictionary of values. |
Quote:
Quote:
Quote:
Quote:
|
Thanks Arevos and Sane, but ConfigParser seems a little too complicated, and I wanted to be able to represent tuples of values by items separated with commas; previously read variables as values prepended with $; comments; and more. So I wrote my own little class:
:
import gimmie |
By the way, for clarifaction, that is not a class. >_>;;
A class is... basically what my code demonstrates. You can create an instance of a class with an object, and call functions of the class as methods. Containing all the individual variables within each individual instance of the class. |
I know what a class is. I get lazy sometimes. :mad:
Although, having thought further on the matter, the script I wrote doesn't address saving new values. That is a problem. A very big one. I may have to go back and look at ConfigParser. In fact, having a human-readable file is more problematic than I thought. I may go back to just using the shelve module. |
| All times are GMT -5. The time now is 12:52 AM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC