免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: xichen
打印 上一主题 下一主题

每周一题——读写配置文件。 [复制链接]

论坛徽章:
0
11 [报告]
发表于 2005-08-24 16:16 |只看该作者

每周一题——读写配置文件。

to sakulagi:

你的程序写法与我的确不同。有一点建议:property在New Style Class 是有特殊用法的,它是一个内置(built-in)方法,最好不用它用为类名。另外你测试的最后一行多了一个';'号

论坛徽章:
0
12 [报告]
发表于 2005-08-24 16:25 |只看该作者

每周一题——读写配置文件。

下面是我根据sakulagi的思路改写的程序:

#! /usr/bin/python

import os
import sys

class Ini:
    """ Assume that property file is "ARG=VALUE" format and no space is allowed on either side of \"=\" """
    def __init__(self, pfile):
        self.items = {}
   
        for line in file(pfile):
            line = line.strip()
            if not line: continue
            if line.startswith('#'): continue
            key, value = line.split('=', 1)
            self.items[key.strip()] = value.strip()
   
    def getdict(self):
        return self.items


if __name__ == "__main__":
    print "Self Test Begin"
    # Generate the test file
    if len(sys.argv) == 1:
        os.system("echo # Comment >; test.properties"
        os.system("echo LOCK=true >;>; test.properties"
        os.system("echo TEST.config.1=234 >;>; test.properties"
        pf = Ini("test.properties";
    else:
        pf = Ini(sys.argv[1])
    print pf.getdict()

这里最后我的生成test.properties与原程序不同,因为发现在里面的双引号也输出到文件中去了,因此我去掉了。

论坛徽章:
0
13 [报告]
发表于 2005-08-24 23:39 |只看该作者

每周一题——读写配置文件。

我的,呵呵,别笑话。
ini文件的格式参照了这里 http://en.wikipedia.org/wiki/Ini_file
也参考了Python的ConfigParser模块的文档

IniFileParser.py

  1. #!C:\Python24\python.exe

  2. import re
  3. import string

  4. NoSectionException = 'NoSectionException'
  5. NoKeyException = 'NoKeyException'

  6. class IniFileParser:
  7.     '''parse ini file described in http://en.wikipedia.org/wiki/Ini_file. no functions for write, only read. :)'''
  8.     def __init__(self):
  9.         self.section_obj = dict()

  10.     def load(self, filename):
  11.         f = open(filename, 'r')
  12.         while 1:
  13.             line = f.readline()
  14.             if not line: break
  15.             line = line.strip('\n')
  16.             line = line.strip()
  17.             # skip comments
  18.             if line == "" or line.startswith(';') or line.startswith('#'):
  19.                 continue
  20.             match_section = re.compile(r'^\[([\w\s\.]*)\]$').match(line)
  21.             if match_section:   # section name line
  22.                 line = match_section.group(1) # get section name
  23.                 sec_keys = dict()
  24.                 self.section_obj[line] = sec_keys
  25.             else:               # key=value line
  26.                 re_comment = re.compile(r'[;#].*')
  27.                 line = re_comment.sub('', line) # remove comments in line
  28.                 [key, value] = map(string.strip, line.split('=', 1))
  29.                 sec_keys[key] = value
  30.                
  31.         f.close()

  32.     def sections(self):
  33.         result = self.section_obj.keys()
  34.         result.sort()
  35.         return result

  36.     def has_section(self, section):
  37.         return section in self.section_obj.keys()

  38.     def keys(self, section):
  39.         if not self.has_section(section): raise NoSectionException
  40.         result = self.section_obj[section].keys()
  41.         result.sort()
  42.         return result

  43.     def has_key(self, section, key):
  44.         return self.section_obj[section].has_key(key)

  45.     def get_value(self, section, key):
  46.         if not self.has_section(section): raise NoSectionException
  47.         if not self.has_key(section, key): raise NoKeyException
  48.         return self.section_obj[section][key]
复制代码


Unit Test: TestIniFileParser.py

  1. #!C:\Python24\python.exe

  2. import unittest
  3. from IniFileParser import *

  4. class TestIniFileParser(unittest.TestCase):
  5.     def setUp(self):
  6.         self.ini = IniFileParser()
  7.         self.ini.load('test.ini')

  8.     def testsections(self):
  9.         self.assertEqual(self.ini.sections(), ['section1', 'section2'])

  10.     def testhassections(self):
  11.         self.assertTrue(self.ini.has_section('section1'))
  12.         self.assertTrue(self.ini.has_section('section2'))
  13.         self.assertFalse(self.ini.has_section('section3'))

  14.     def testkeys(self):
  15.         self.assertEqual(self.ini.keys('section1'), ['var1', 'var2'])
  16.         self.assertEqual(self.ini.keys('section2'), ['var1', 'var2'])
  17.         self.assertRaises(NoSectionException, self.ini.keys, 'section3')

  18.     def testhaskey(self):
  19.         self.assertTrue(self.ini.has_key('section1', 'var1'))
  20.         self.assertTrue(self.ini.has_key('section1', 'var2'))
  21.         self.assertTrue(self.ini.has_key('section2', 'var1'))
  22.         self.assertTrue(self.ini.has_key('section2', 'var2'))

  23.     def testgetvalue(self):
  24.         self.assertEqual(self.ini.get_value('section1', 'var1'), 'foo')
  25.         self.assertEqual(self.ini.get_value('section1', 'var2'), 'doodle')
  26.         self.assertEqual(self.ini.get_value('section2', 'var1'), 'baz')
  27.         self.assertEqual(self.ini.get_value('section2', 'var2'), 'shoodle')
  28.         self.assertRaises(NoSectionException, self.ini.get_value, 'section3', 'var1')
  29.         self.assertRaises(NoKeyException, self.ini.get_value, 'section1', 'var3')

  30. if __name__ == '__main__':
  31.     #unittest.main()
  32.     suite = unittest.makeSuite(TestIniFileParser)
  33.     unittest.TextTestRunner(verbosity=2).run(suite)
复制代码


ini file for test: test.ini
[section1]

; some comment on section1
var1 = foo
var2 = doodle ; some comment on section1.var2

[section2]

# some comment on section2
var1 = baz # some comment on section2.var1
var2 = shoodle

# [section3]
# var1 = bar
; var2 =

论坛徽章:
0
14 [报告]
发表于 2005-08-25 07:58 |只看该作者

每周一题——读写配置文件。

原帖由 "limodou" 发表:
to sakulagi:

你的程序写法与我的确不同。有一点建议:property在New Style Class 是有特殊用法的,它是一个内置(built-in)方法,最好不用它用为类名。另外你测试的最后一行多了一个';'号
我也猜这么好听的名字一定有人用过了,呵呵

分号是因为我是一直写Java程序的 ,所以习惯了

论坛徽章:
0
15 [报告]
发表于 2005-08-25 07:59 |只看该作者

每周一题——读写配置文件。

原帖由 "limodou" 发表:
print pf.getdict()

这里最后我的生成test.properties与原程序不同,因为发现在里面的双引号也输出到文件中去了,因此我去掉了。
还是用循环看着简洁。我本来想练习一下map(),结果不会写lambda函数,最后越写感觉越诡秘。嘿嘿

论坛徽章:
0
16 [报告]
发表于 2005-08-25 08:02 |只看该作者

每周一题——读写配置文件。

[quote]原帖由 "wolfg"][/quote 发表:
相比之下俺写的果然简陋,嘿嘿。

论坛徽章:
0
17 [报告]
发表于 2005-08-27 16:19 |只看该作者

每周一题——读写配置文件。

什么是自测试代码?不理解自测的功能?

论坛徽章:
0
18 [报告]
发表于 2005-08-28 21:42 |只看该作者

每周一题——读写配置文件。

Python 的两个用于单元测试的标准模块:unittest和doctest。这些模块扩展了用来确认函数内部的先置条件和后置条件的内置 assert 语句的能力。
由于模块是被import的,那么需要在直接运行该模块的时候检查必须的环境是否具备,并运行一段测试代码确保程序无错误.
一般采用

if __name__ == "__main__":
    测试代码
这样的方法.

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:55:28
19 [报告]
发表于 2005-08-29 09:32 |只看该作者

每周一题——读写配置文件。

学习

论坛徽章:
0
20 [报告]
发表于 2005-08-29 11:44 |只看该作者

每周一题——读写配置文件。

只是我的看法而已,其实各位写的都有自己的特色。

config.py,这个是模块
  1. # -*- coding: cp936 -*-

  2. """
  3. 本程序为MIT授权
  4. 作者:梅劲松
  5. """

  6. """
  7. The MIT License

  8. Copyright (c) 2005 stephen.cn@gmail.com

  9. 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:

  10. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

  11. 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.


  12. Read config module.

  13. """

  14. __all__ = ['read_config']
  15. __version__ = '1.0'

  16. def read(file=''):
  17.     '''File name. String'''
  18.     if file=='':
  19.         return ('不能打开配置文件,请检查目录中是否有%s这个文件。\n' % file)
  20.     else:
  21.         config = get(file)
  22.         if not config:
  23.             return ('不能打开配置文件,请检查目录中是否有%s这个文件。\n' % file)
  24.         else:
  25.             return config
  26.             
  27. def get(file):
  28.     try:
  29.             fd = open(file)
  30.     except:
  31.             return None
  32.     lines = fd.readlines()
  33.     config = {}
  34.     for i in lines:
  35.             i = i.strip()
  36.             if i.find('=') < 0:
  37.                     continue
  38.             if i[0] == '#':
  39.                     continue
  40.             var, value = i.split('=',1)
  41.             var = var.strip()
  42.             value = value.split('=')
  43.             config[var] = value
  44.     return config


  45. def _test():
  46.     import doctest, config
  47.     return doctest.testmod(config)


  48. if __name__ == "__main__":
  49.     _test()
复制代码


然后还有test.txt这个用来测试的文件

  1. name=梅劲松
  2. age=32
  3. sex=男
  4. iq=傻瓜
复制代码

然后测试方式为在msdos方式下:

  1. D:\>;python config.py -v
  2. Running config.__doc__
  3. 0 of 0 examples failed in config.__doc__
  4. Running config._test.__doc__
  5. 0 of 0 examples failed in config._test.__doc__
  6. Running config.get.__doc__
  7. 0 of 0 examples failed in config.get.__doc__
  8. Running config.read.__doc__
  9. 0 of 0 examples failed in config.read.__doc__
  10. 4 items had no tests:
  11.     config
  12.     config._test
  13.     config.get
  14.     config.read
  15. 0 tests in 4 items.
  16. 0 passed and 0 failed.
  17. Test passed.

  18. D:\>;
复制代码

使用方法为

  1. D:\>;python
  2. Python 2.3.3 (#51, Dec 18 2003, 20:22:39) [MSC v.1200 32 bit (Intel)] on win32
  3. Type "help", "copyright", "credits" or "license" for more information.
  4. >;>;>; import config
  5. >;>;>; conf=config.read('test.txt')
  6. >;>;>; conf['ai']
  7. ['\xc9\xb5\xb9\xcf']
  8. >;>;>;
复制代码


欢迎大家指正。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP