Cheng Tang | 24c9e27 | 2013-08-28 22:15:45 +0800 | [diff] [blame] | 1 | #-*- coding: utf-8 |
| 2 | import fileinput |
| 3 | import os |
| 4 | |
| 5 | |
| 6 | def parse_config_file(config_file, configs, encoding='utf-8'): |
| 7 | if not os.path.exists(config_file): |
| 8 | print u"Config file <{0}> not exists".format(config_file) |
| 9 | return False |
| 10 | if isinstance(config_file, str): |
| 11 | config_file = config_file.decode(encoding) |
| 12 | |
| 13 | lineno = 0 |
| 14 | for line in fileinput.input(config_file): |
| 15 | lineno += 1 |
| 16 | line = line.strip(' ').rstrip('\n').rstrip('\r') |
| 17 | line = line.decode(encoding) |
| 18 | if not line: |
| 19 | continue |
| 20 | if line.startswith('#'): |
| 21 | # is comment |
| 22 | continue |
| 23 | cfg = line.partition('=') |
| 24 | if not cfg[1]: |
| 25 | raise ValueError(u"Config file line %d error" % lineno) |
| 26 | configs[cfg[0].strip(' ')] = cfg[2].lstrip(' ') |
| 27 | return True |