-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfigparser_defaults.py
More file actions
59 lines (48 loc) · 1.54 KB
/
configparser_defaults.py
File metadata and controls
59 lines (48 loc) · 1.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import configparser
option_names = [
"from-default",
"from-section",
"section-only",
"file-only",
"init-only",
"init-and-file",
"from-vars",
]
# Initialize the parser with some defaults
DEFAULTS = {
"from-default": "value from defaults passed to init",
"init-only": "value from defaults passed to init",
"init-and-file": "value from defaults passed to init",
"from-section": "value from defaults passed to init",
"from-vars": "value from defaults passed to init",
}
parser = configparser.ConfigParser(defaults=DEFAULTS)
print("Defaults before loading file:")
defaults = parser.defaults()
for name in option_names:
if name in defaults:
print("{:<15} = {!r}".format(name, defaults[name]))
# Load the configuration file
parser.read("test7.ini")
print("\nDefaults after loading file:")
defaults = parser.defaults()
for name in option_names:
if name in defaults:
print("{:<15} = {!r}".format(name, defaults[name]))
# Define some local overrides
vars = {"from-vars": "value from vars"}
# Show the values of all the options
print("\nOption lookup:")
for name in option_names:
value = parser.get("sect", name, vars=vars)
print("{:<15} = {!r}".format(name, value))
# Show error messages for options that do not exist
print("\nError cases: ")
try:
print("No such option: ", parser.get("sect", "no-option"))
except configparser.NoOptionError as err:
print(err)
try:
print("No such section: ", parser.get("no-sect", "no-option"))
except configparser.NoSectionError as err:
print(err)