- 论坛徽章:
- 0
|
每周一题——读写配置文件。
只是我的看法而已,其实各位写的都有自己的特色。
config.py,这个是模块
- # -*- coding: cp936 -*-
- """
- 本程序为MIT授权
- 作者:梅劲松
- """
- """
- The MIT License
- Copyright (c) 2005 stephen.cn@gmail.com
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- Read config module.
- """
- __all__ = ['read_config']
- __version__ = '1.0'
- def read(file=''):
- '''File name. String'''
- if file=='':
- return ('不能打开配置文件,请检查目录中是否有%s这个文件。\n' % file)
- else:
- config = get(file)
- if not config:
- return ('不能打开配置文件,请检查目录中是否有%s这个文件。\n' % file)
- else:
- return config
-
- def get(file):
- try:
- fd = open(file)
- except:
- return None
- lines = fd.readlines()
- config = {}
- for i in lines:
- i = i.strip()
- if i.find('=') < 0:
- continue
- if i[0] == '#':
- continue
- var, value = i.split('=',1)
- var = var.strip()
- value = value.split('=')
- config[var] = value
- return config
- def _test():
- import doctest, config
- return doctest.testmod(config)
- if __name__ == "__main__":
- _test()
复制代码
然后还有test.txt这个用来测试的文件
- name=梅劲松
- age=32
- sex=男
- iq=傻瓜
复制代码
然后测试方式为在msdos方式下:
- D:\>;python config.py -v
- Running config.__doc__
- 0 of 0 examples failed in config.__doc__
- Running config._test.__doc__
- 0 of 0 examples failed in config._test.__doc__
- Running config.get.__doc__
- 0 of 0 examples failed in config.get.__doc__
- Running config.read.__doc__
- 0 of 0 examples failed in config.read.__doc__
- 4 items had no tests:
- config
- config._test
- config.get
- config.read
- 0 tests in 4 items.
- 0 passed and 0 failed.
- Test passed.
- D:\>;
复制代码
使用方法为
- D:\>;python
- Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32
- Type "help", "copyright", "credits" or "license" for more information.
- >;>;>; import config
- >;>;>; conf=config.read('test.txt')
- >;>;>; conf['ai']
- ['\xc9\xb5\xb9\xcf']
- >;>;>;
复制代码
欢迎大家指正。 |
|