python 关于配置文件,日志,传参总结
前段时间用python做了些工作,说实在的,之前也就是了解一点python,没有用其做过东西,这次做完之后,感觉python脚本挺强大的,在日志,配置,字符处理与mysql的连接都做得比较好。现将其总结下
一、python的日志功能
只要在程序中添加import logging,就可以使用其日志功能,其日志级别包括:日志级别包括:NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
在程序中可以指定日志终端的输出级别和写日志的级别,可以完美的把日志按照要求输入到终端和写入指定文件
Demo:
#!/usr/bin/python
#encoding=utf-8
import logging
#日志级别包括:NOTSET < DEBUG < INFO < WARNING < ERROR < CRITICAL
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S',
filename='myapp.log',#定义日志的名称
filemode='w')
#################################################################################################
#定义一个StreamHandler,将INFO级别或更高的日志信息打印到标准错误,并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.ERROR)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
#################################################################################################
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('This is error message')
logging.critical('This is critical message')
for i in range(0,10):
logging.info(str(i))
运行:python log.py
终端输出:由于日志中设定了终端输出日志的级别为ERROR,所以终端只输出大于该级别的日志,大于INFO级别的日志写在了指定的myapp.log文件中
二、python读取配置文件功能
只要在程序中添加import ConfigParser,就可以使用python自带的读取配置文件功能
Demo:
假设配置文件名称为:config,其内容为:
[computer]
ip=localhost ;本地数据库
port = 80 ;端口
程序:
#!/usr/bin/python
#encoding=utf-8
import ConfigParser
#读取配置文件
config = ConfigParser.ConfigParser()
config.readfp(open("config","rb"))
g_ip = config.get("computer","ip")
g_port = config.get("computer","port")
print "IP:",g_ip,"PORT:",g_port
运行python config.py:
输出结果:
三、python main函数传参
如C/C++一样,main函数传参使用的也是getopt
需要模块:sys
参数个数:len(sys.argv)
脚本名: sys.argv[0]
参数1: sys.argv[1]
参数2: sys.argv[2]
Demo:
#!/usr/bin/python
#encoding=utf-8
import os,sys,getopt
def Usage():
print "Usage:%s -h 帮助信息\t-b 查询的开始日期\t-e 查询的结束日期"%sys.argv[0]
#main 函数执行
if __name__=="__main__":
#对输入的参数进行判断
try:
opts,args = getopt.getopt(sys.argv[1:], "hb:e:")
print "输入的参数个数为:%s\r\n"%len(sys.argv)
for op, value in opts:
if op == "-b":
print "input arg:%s\r\n"%value
if op == "-e":
print "input arg:%s\r\n"%value
elif op == "-h":
Usage()
sys.exit()
except getopt.GetoptError:
print "getopt error!"
Usage()
sys.exit()
运行:python getarg.py –h
运行结果:
运行:python getarg.py -b 2012 -e 2013