python典型应用场景、domo及模板之一-----------配置&日志

Python处理配置与日志

线上脚本比较常见的几个功能点包括:读取命令行,读取配置文件,写日志文件,下面逐一介绍,介绍采用示例代码的形式。

1 Optparse 解析命令行参数模块

Optparse模块可以解析程序的命令行参数,用法如下:
1
2
3
4
5
6
7
def _init_opt():
     #解析命令行,配置文件选项
     import optparse
     parser = optparse.OptionParser()
     parser.add_option( '-c' , '--config' , action= "store" , dest= "config" , default = "./conf/xxx.conf" , help= "config file path" )
     options, remainder = parser.parse_args()
     return options
之后输入:
1
2
3
4
<yourscript> --config=myconfig
<yourscript> --config myconfig
<yourscript> -c myconfig
<yourscript> -cmyconfig
这几个命令效果是相同的。

使用optparse模块的步骤如下: 首先,必须 import OptionParser类,创建一个 OptionParser对象:

1
2
3
from optparse import OptionParser
[...]
parser = OptionParser()
然后,使用 add_option 来定义命令行参数:
1
2
parser.add_option(opt_str, ...,
                   attr=value, ...)
每个命令行参数就是由参数名字符串和参数属性组成的。如 -f 或者 –file 分别是长短参数名:
1
parser.add_option( "-f" , "--file" , ...)
最后,一旦你已经定义好了所有的命令行参数,调用 parse_args() 来解析程序的命令行:
1
(options, args) = parser.parse_args()
注: 你也可以传递一个命令行参数列表到 parse_args();否则,默认使用 sys.argv[:1]。 parse_args() 返回的两个值:
  1. options,它是一个对象(optpars.Values),保存有命令行参数值。只要知道命令行参数名,如 file,就可以访问其对应的值: options.file 。
  2. args,它是一个由 positional arguments 组成的列表。
有关optparse模块的更详细信息请参考: http://docs.python.org/library/optparse.html

2 ConfigParser读、写配置文件模块

ConfigParser模块用来解析配置文件,配置文件格式如下:
1
2
3
4
5
6
7
8
9
10
[file]
# 注释而已
rel_file = ./relfile
word_file = ./wordfile
 
[thres]
word_freq_thres = 200
 
[log]
log_file = ./log/delhighfreq.log
读取该配置文件的代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def _init_conf(options):
     #读取配置文件
     import ConfigParser
     configfile = options.config
 
     config = ConfigParser.ConfigParser()
     config.read([configfile])
 
     # 读取三个配置项
     conf_ok = []
     conf_ok.append(config.get( "log" , "log_file" ))
     conf_ok.append(config.get( "file" , "rel_file" ))
     conf_ok.append(config.get( "file" , "word_file" ))
     thres = config.getint( "thres" , "word_freq_thres" )
     conf_ok.append(thres)
return conf_ok
有关ConfigParser的更多信息请参考: http://docs.python.org/library/configparser.html

3 logging 日志模块

Logging模块使用起来非常简单方便,示例代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def _init_log(logfile):
     # 生成log对象
     logger = logging.getLogger()
# 日志打印到磁盘;默认输出模式为 'a' (文件末尾追加写)
# 除了FileHandler,还支持SocketHandler, SMTPHandler等
     hdlr = logging.FileHandler(logfile)
# 设置日志格式
     formatter = logging.Formatter( '%(asctime)s %(levelname)s %(message)s' )
     hdlr.setFormatter(formatter)
     logger.addHandler(hdlr)
     logger.setLevel(logging.DEBUG)
 
return logger
 
# 下面是使用logger打印日志
def run():
     logger = _init_log(logfile)
     logger.debug(“debug info”)
     logger.info( "info message" )
     …………
logging支持的日志格式参见:http://docs.python.org/library/logging.html#formatter-objects

logging还支持用配置文件初始化,如下:

1
2
3
4
5
6
7
8
9
10
import logging
import logging.config
 
logging.config.fileConfig( "logging.conf" )
 
# create logger
logger = logging.getLogger( "simpleExample" )
 
# "application" code
logger.debug( "debug message" )
配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
[loggers]
keys=root,simpleExample
 
[handlers]
keys=consoleHandler
 
[formatters]
keys=simpleFormatter
 
[logger_root]
level=DEBUG
handlers=consoleHandler
 
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate= 0
 
[handler_consoleHandler]
class =StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
 
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=
有关logging模块的更多信息请参考:http://docs.python.org/library/logging.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值