Skip to content

Commit c0ad2ac

Browse files
committed
Added sample script for ConfigParser
1 parent a7f2be8 commit c0ad2ac

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

conf-sample.py

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#!/bin/env python
2+
#
3+
# conf-sample.py - Read and write configuration files
4+
#
5+
# This script is an example for a config parser
6+
#
7+
# Author: Jan Beilicke <dev@jotbe-fx.de>
8+
# Date created: 2011-03-31
9+
#
10+
# == Use cases ==
11+
#
12+
# - Read a default config from a template
13+
# - Edit and add config sections and items
14+
# - Write changed values to config file
15+
#
16+
# == Sample config ==
17+
#
18+
# # Test config for conf.py, save it as 'conf.ini'
19+
# [global]
20+
# spam = Ni!
21+
# eggs = foo, bar
22+
# max_eggs = 10
23+
#
24+
# [specific]
25+
# max_knights = 15
26+
#
27+
28+
import ConfigParser
29+
import io
30+
from types import *
31+
32+
confFile = 'conf.ini'
33+
conf = '''
34+
[global]
35+
spam = Ni!
36+
eggs = foo, bar
37+
max_eggs = 5
38+
skip_bridge
39+
40+
[specific]
41+
max_knights = 15
42+
'''
43+
44+
config = ConfigParser.RawConfigParser(allow_no_value = True)
45+
46+
# Read the config
47+
# Switch the comments of the following two lines if you want to read
48+
# from confFile
49+
config.read(confFile)
50+
#config.readfp(io.BytesIO(conf))
51+
52+
print config.get('global', 'eggs').split(',')
53+
print 'Max eggs: ', config.getint('global', 'max_eggs')
54+
# Get item without value, returns either True or False
55+
print 'Skip bridge: ', (type(config.get('global', 'skip_bridge')) == NoneType)
56+
57+
# Add new section
58+
sec = 'new_section'
59+
try:
60+
config.add_section(sec)
61+
except ConfigParser.DuplicateSectionError:
62+
print 'Section %s exists ... updating ...' % sec
63+
64+
config.set('new_section', 'life', 'brian')
65+
config.set('new_section', 'favorite_color', 'blue')
66+
67+
# Edit existing section
68+
config.set('global', 'max_eggs', 20)
69+
print 'Max eggs: ', config.getint('global', 'max_eggs')
70+
71+
# Write to file
72+
with open(confFile, 'wb') as configfile:
73+
config.write(configfile)
74+
75+
print 'Done.'

0 commit comments

Comments
 (0)