9. if __name__ == '__main__' : do something ; __name__ 是Python模块的内置属性。每个python模块都是一个.py文件,既可以从命令行运行,又可以导入其他模块。当从命令行运行时,__name__ == ‘__main__’ , do something 会执行; 当导入其他模块时, __name__ 的值为模块的名称, 不等于‘ __main__ ’, do something 不会执行。也就是说,该模块存在某些语句,当自身单独运行时,期望被执行,而作为支持模块导入其他模块时,却不希望执行。 因此, 这条语句通常可用于单独运行和测试该模块。
10. 下面的例子演示了Python 提供的一些基本语言特性: 缩进,内置数据结构, 控制流, 读写文件,重定向, 导入模块, 类定义, 异常机制,日志,正则表达式。代码本身没有什么创新之处,但整合到一起,可以演示Python 的大部分基本语言特性。
dupkeys.py
- ##################################################################
- #
- # validate if the input text file contains duplicated keys.
- # the input.txt should like below:
- # key1 value1
- # key2 value2
- # ...
- #
- # the result is stored into a hashtable:
- # {key: [count, [value1, value2,..,valueN]]}
- #
- ##################################################################
- import sys
- import re
- from thelog import initlog
- from exc import NotMatchedException
- patt = re.compile(r'^\s*(\w+)\s+(\w+)[\s\r\n]+$')
- total_items = 0
- count = { }
- def proc(line) :
- matched = patt.match(line)
- try :
- if matched :
- global total_items
- total_items += 1
- key = matched.group(1)
- value = matched.group(2)
- if key in count :
- valuelist = (count[key])[1]
- valuelist.append(value)
- count[key] = [(count[key])[0]+1, valuelist]
- else :
- count[key] = [1, [value]]
- else :
- raise NotMatchedException('The line Not matched: %s' % line)
- except (NotMatchedException, Exception), args:
- dupkeysLog.error(args)
- if len(sys.argv) != 2 :
- print "usage: python dupkeys.py filename.txt "
- sys.exit(1)
- logfile = 'dupkeys.log'
- dupkeysLog = initlog(logfile)
- resfile = open('result.txt', 'w')
- sysStdout = sys.stdout
- sys.stdout = resfile # redirect stdout into file result.txt
- filename = sys.argv[1]
- inputfile = open(filename)
- for line in inputfile :
- proc(line)
- print "total items in file %s : %d" % (filename, total_items)
- dupkeysLog.error("Keys duplicated: ")
- for k, v in count.iteritems() :
- print k, v
- if v[0] > 1 :
- dupkeysLog.error( ' %s %s ' % (k, v) )
- if inputfile:
- inputfile.close()
- if resfile :
- resfile.close()
- sys.stdout = sysStdout
thelog.py
- import logging
- LOG_LEVELS = {
- 'DEBUG': logging.DEBUG, 'INFO': logging.INFO,
- 'WARN': logging.WARNING, 'ERROR': logging.ERROR,
- 'CRITICAL': logging.CRITICAL
- }
- def initlog(filename) :
- logger = logging.getLogger()
- hdlr = logging.FileHandler(filename)
- formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
- hdlr.setFormatter(formatter)
- logger.addHandler(hdlr)
- logger.setLevel(LOG_LEVELS['ERROR'])
- return logger
- if __name__ == '__main__' :
- errlog = initlog("errlog.log")
- errlog.info('this is an ordinary info')
- errlog.warn('this is a warning')
- errlog.error('this is an error that should be handled')
- errlog.critical('this is an severe error')
exc.py
- class MyException(Exception) : pass
- class MsgException(MyException) :
- def __init__(self, msg) :
- self.msg = msg
- def __str__(self) :
- return repr(self.msg)
- class NotMatchedException(MsgException) : pass
