cfg2str()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
c 2
b 0
f 0
dl 0
loc 6
rs 9.4285
1
#!/usr/bin/env python
2
try:
3
    from ConfigParser import ConfigParser  # python2
4
except ImportError:
5
    from configparser import ConfigParser  # python3
6
try:
7
    import StringIO
8
except ImportError:
9
    import io
10
11
12
def text_stream():
13
    try:
14
        StringIO.StringIO()
15
    except NameError:
16
        return io.StringIO()
17
18
19
def cfg2str(config):
20
    output = text_stream()
21
    config.write(output)
22
    value = output.getvalue()
23
    output.close()
24
    return value
25
26
27
def dict2list(value):
28
    for k, v in value.items():
29
        yield "%s = %s" % (k, v)
30
31
32
def item2str(value):
33
    if isinstance(value, list):
34
        return "\n%s" % "\n".join(value).replace("\n", "\t\n")
35
    if isinstance(value, dict):
36
        return item2str(list(dict2list(value)))
37
    return str(value)
38
39
40
def dict2cfg(config_dict):
41
    config = ConfigParser()
42
    for section, value in config_dict.items():
43
        config[section] = dict()
44
        for k, v in config_dict[section].items():
45
            if v:  # skip empty
46
                config[section][k] = item2str(v)
47
    return cfg2str(config)
48