Pyfig: A simple config file parser for python
- Project by Alec Henriksen <firstname.lastname@example.org>
- License: GNU GPL
- Website: http://pyfig.alecwh.com/
- Version: 2.0 (09/27/2009)
- Development: http://bitbucket.org/alecwh/pyfig/
- Easy to use (straightforward, simple)
- Supports categories/sections in the config file
- Supports comments
- Very robust in terms of parsing
- One file, no package
Simply drop pyfig.py inside your working directory, or somewhere in your python search path. Pyfig doesn't have any dependencies.
Pyfig is released under the GNU GPL (General Public License). See LICENSE for more information.
Example and Usage
The `EXAMPLE_CONFIG` file can be used to test/play with Pyfig.
First, you need to import Pyfig into your program:
Next, you need to create the Pyfig object. In order to do this, you need to pass the filepath of the config file you want to parse. I'll use the EXAMPLE_CONFIG included.
config = pyfig.Pyfig("EXAMPLE_CONFIG")
That's it. You've just created a Pyfig instance which contains all the data in EXAMPLE_CONFIG. Pyfig organizes config values by category, so in order to access player_name under category general, you would do this:
print config.general.player_name 'toaster_phun'
There is also an age value in that category. We can access that like this:
print config.general.age 19
You can also iterate through categories! This is useful when you don't know what or how many config values exist in a given category. You iterate like this:
- for x, y in config.general:
- print "%s ---> %s" % (x, y)
age ---> 19 player_name ---> toaster_phun
The entire config object is also an iterable. It will return a tuple for each category; the name of the category and the actual object:
- for x, y in config:
print "%s: %s" % (x, y)
bank: <pyfig.ConfigCategory object at 0xb7d8692c> connection: <pyfig.ConfigCategory object at 0xb7d8990c> general: <pyfig.ConfigCategory object at 0xb7d867ec>
Pyfig and Type Detection
Pyfig does not automatically detect types. If you would like Pyfig to turn a value into something other than a string (the default type for values), it must be specified in the config file. By default, the following value, 19, will be a string:
player_age = 19
If you want 19 to be an integer inside your config object, you must add this:
player_age/int = 19
Or a float:
player_age/float = 19
Or a boolean:
apply_advanced_graphics/bool = True
### Warning ### Boolean values should only be "True" or "False". Anything besides False will be returned as True. (So don't misspell False!)
API Changes since 1.x
Pyfig has undergone a major API re-design since the 1.x series. To get a full documentation, see the Example and Usage section above.
Config values are now stored as objects in category objects. You grab a value by:
>>> print Pyfig.general.age 16
Config categories are also iterables. You can do this:
>>> for x, y in Pyfig.general ... print x, y age 19 player_name toaster_phun