Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from __future__ import division 

2 

3try: 

4 import configparser 

5except ImportError: 

6 import ConfigParser as configparser 

7 

8__all__ = ["read_conf_file"] 

9 

10 

11def read_conf_file(filename): 

12 """Read the new type of configuration file. 

13 

14 This function reads the new type of configuration file that contains sections. It also 

15 has the capability to take parameters as math expressions and lists. String entries in 

16 list parameters do not need to be surrounded by quotes. An example file is shown below: 

17 

18 | [section] 

19 | # Floating point parameter 

20 | var1 = 1.0 

21 | # String parameter 

22 | var2 = help 

23 | # List of strings parameter 

24 | var3 = [good, to, go] 

25 | # List of floats parameter 

26 | var4 = [1, 2, 4] 

27 | # Boolean parameter 

28 | var5 = True 

29 | # Floating point math expression parameter 

30 | var6 = 375. / 30. 

31 | # Set of tuples 

32 | var7 = (test1, 1.0, 30.0), (test2, 4.0, 50.0) 

33 

34 Parameters 

35 ---------- 

36 filename : str 

37 The configuration file name. 

38 

39 Returns 

40 ------- 

41 dict 

42 A dictionary from the configuration file. 

43 """ 

44 config = configparser.ConfigParser() 

45 config.read(filename) 

46 

47 from collections import defaultdict 

48 config_dict = defaultdict(dict) 

49 math_ops = "+,-,*,/".split(',') 

50 import re 

51 paren_match = re.compile(r'\(([^\)]+)\)') 

52 

53 for section in config.sections(): 

54 for key, _ in config.items(section): 

55 try: 

56 value = config.getboolean(section, key) 

57 except ValueError: 

58 try: 

59 value = config.getfloat(section, key) 

60 except ValueError: 

61 value = config.get(section, key) 

62 

63 # Handle parameters with math operations 

64 check_math = [op for op in math_ops if op in value] 

65 if len(check_math): 

66 try: 

67 value = eval(value) 

68 except NameError: 

69 pass 

70 

71 try: 

72 # Handle lists from the configuration 

73 if value.startswith('['): 

74 value = value.strip('[]') 

75 try: 

76 value = [float(x) for x in value.split(',')] 

77 except ValueError: 

78 value = [str(x.strip()) for x in value.split(',')] 

79 if len(value) == 1: 

80 if value[0] == '': 

81 value = [] 

82 if value.startswith('('): 

83 val_parts = [] 

84 matches = paren_match.findall(value) 

85 for match in matches: 

86 parts_list = [] 

87 parts = match.split(',') 

88 for part in parts: 

89 try: 

90 parts_list.append(float(part)) 

91 except ValueError: 

92 parts_list.append(str(part.strip())) 

93 val_parts.append(tuple(parts_list)) 

94 value = val_parts 

95 except AttributeError: 

96 # Above was a float 

97 pass 

98 

99 config_dict[section][key] = value 

100 

101 return config_dict