python_day6学习笔记
一、Logger模块
- logging.basicConfig函数
可通过具体参数来更改logging模块默认行为,可用参数有
filename: 用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode: 文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format: 指定handler使用的日志显示格式。
datefmt: 指定日期时间格式。
level: 设置rootlogger的日志级别
stream: 用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET format参数中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 数字形式的日志级别
%(levelname)s 文本形式的日志级别
%(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
%(filename)s 调用日志输出函数的模块的文件名
%(module)s 调用日志输出函数的模块名
%(funcName)s 调用日志输出函数的函数名
%(lineno)d 调用日志输出函数的语句所在的代码行
%(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
%(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
%(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
%(thread)d 线程ID。可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s 用户输出的消
举例:
import logging
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
logging.error('error message')
logging.critical('critical message')
结果:
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:13] DEBUG : This is debug message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:14] INFO : This is info message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:15] WARNING : This is warning message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:16] ERROR : error message
[root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:17] CRITICAL: critical message
logging分为4个模块: loggers, handlers, filters, and formatters
● loggers: 提供应用程序调用的接口
● handlers: 把日志发送到指定的位置
● filters: 过滤日志信息
● formatters: 格式化输出日志
Logger
Logger.setLevel() 设置日志级别
Logger.addHandler()和Logger.removeHandler() 增加和删除日志处理器
Logger.addFilter()和Logger.removeFilter() 增加和删除过滤器
Logger.debug(), Logger.info(), Logger.warning(), Logger.error(), and Logger.critical() 创建不同的级别的日志
getLogger() 获取日志的根实例
Handler
setLevel() 设置日志级别
setFormatter() 设置输出格式
addFilter() and removeFilter() 增加和删除过滤器
Formatter
默认形式为: %Y-%m-%d %H:%M:%S.
格式为: %()s
- logging.getLogger函数
import logging
log = logging.getLogger('yinjia')
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') log.debug('This is debug message')
log.info('This is info message')
log.warning('This is warning message')
log.error('error message')
log.critical('critical message')
输出结果:
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:12] DEBUG : This is debug message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:13] INFO : This is info message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:14] WARNING : This is warning message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:15] ERROR : error message
[yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:16] CRITICAL: critical message
返回一个logger对象,如果没有指定名字将返回root logger
- logging.getLogger函数
以ERROR级别记录日志消息,异常跟踪信息将被自动添加到日志消息里。Logger.exception通过用在异常处理块中,例如:
import logging
log = logging.getLogger('yinjia')
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') try:
raise Exception,'This is a exception'
except:
log.exception('This is debug message') #异常信息被自动添加到日志消息中 输出结果:
[yinjia]:[2015-07-03 14:24:43] [test12.py|<module>] [line:15] ERROR : This is debug message
Traceback (most recent call last):
File "D:/PycharmProjects/untitled/test12.py", line 13, in <module>
raise Exception,'This is a exception'
Exception: This is a exception
- 其它函数
import logging
log = logging.getLogger('yinjia')
logging.basicConfig(level=logging.DEBUG,
format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
filename='myapp.log',
filemode='w') # 再创建一个handler,用于输出到控制台
console = logging.StreamHandler()
# 定义handler的输出格式formatter
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
# 给logging添加handler
logging.getLogger('').addHandler(console)
logging.info('Jackdaws love my big sphinx of quartz.') log.debug('This is debug message')
log.info('This is info message')
log.warning('This is warning message')
log.error('error message')
log.critical('critical message') 控制台输出结果:
root : INFO Jackdaws love my big sphinx of quartz.
yinjia : INFO This is info message
yinjia : WARNING This is warning message
yinjia : ERROR error message
yinjia : CRITICAL critical message
文件输出结果同上例,只多了一行root用户记录。
另一种方法举例:
import logging
# 创建一个logger
logger = logging.getLogger('yinjia')
logger.setLevel(logging.DEBUG) format = '[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s'
fmt = '[%(asctime)-12s] [%(filename)s][line:%(lineno)d] [%(levelname)8s]: %(message)s' # 创建一个handler,用于输出到控制台
console = logging.StreamHandler() # 创建一个handler,用于写入日志文件
fp = logging.FileHandler('D:\PycharmProjects\untitled\myapp.log') # 定义handler的输出格式formatter
formatter = logging.Formatter(fmt)
fpmatter = logging.Formatter(format)
console.setFormatter(formatter)
fp.setFormatter(fpmatter) # 给logging添加handler
logger.addHandler(console)
logger.addHandler(fp) # 记录日志
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
logger.error('error message')
logger.critical('critical message')
以上可以同时输出到控制台和LOG日志文件。
流程:创建logger->创建handler->定义handler输出格式->给logging添加handler->记录日志
二、XML模块
- 生成XML文件
主要方法:
1、生成XML节点(node)
createElement(“node_name”)
2、给节点添加属性值(Attribute)
node.setAttribute(“att_name”,”arr_value”)
3、节点的标签值(data)
createTextNode(“node_value”)
其中第1、3点创建完节点(节点值)之后,还需使用下面的方法添加到指点的节点位置下面:
prev_node.appendChild(cur_node)
这里的prev_node要添加节点的上一层节点,而cur_node即为当前要添加的节点了。
举例如下:
from xml.dom import minidom
import os
import os.path filename = os.getcwd() + os.path.sep
print filename doc = minidom.Document()
doc.appendChild(doc.createComment("This is a simple xml."))
booklist = doc.createElement("booklist")
doc.appendChild(booklist) def addBook(newbook):
book = doc.createElement("book")
book.setAttribute("id",newbook["id"]) title = doc.createElement("title")
title.appendChild(doc.createTextNode(newbook["title"]))
book.appendChild(title) author = doc.createElement("author")
name = doc.createElement("name")
firstname = doc.createElement("firstname")
firstname.appendChild(doc.createTextNode(newbook["firstname"]))
lastname = doc.createElement("lastname")
lastname.appendChild(doc.createTextNode(newbook["lastname"]))
name.appendChild(firstname)
name.appendChild(lastname)
author.appendChild(name)
book.appendChild(author) pubdate = doc.createElement("pubdate")
pubdate.appendChild(doc.createTextNode(newbook["pubdate"]))
book.appendChild(pubdate) booklist.appendChild(book) addBook({"id":"","title":"An apple","firstname":"Peter","lastname":"Zhang","pubdate":"2012-1-12"})
addBook({"id":"","title":"Love","firstname":"Mike","lastname":"Li","pubdate":"2012-1-10"})
addBook({"id":"","title":"Steve.Jobs","firstname":"Tom","lastname":"Wang","pubdate":"2012-1-19"})
addBook({"id":"","title":"Harry Potter","firstname":"Peter","lastname":"Chen","pubdate":"2012-11-11"}) f = file(filename + "book.xml","w")
doc.writexml(f)
f.close()
运行结果如下:
生成XML文件如下:
<?xml version="1.0" ?>
<!--This is a simple xml.-->
<booklist>
<book id="">
<title>An apple</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Zhang</lastname>
</name>
</author>
<pubdate>2012-1-12</pubdate>
</book> <book id="">
<title>Love</title>
<author>
<name>
<firstname>Mike</firstname>
<lastname>Li</lastname>
</name>
</author>
<pubdate>2012-1-10</pubdate>
</book> <book id="">
<title>Steve.Jobs</title>
<author>
<name>
<firstname>Tom</firstname>
<lastname>Wang</lastname>
</name>
</author>
<pubdate>2012-1-19</pubdate>
</book> <book id="">
<title>Harry Potter</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Chen</lastname>
</name>
</author>
<pubdate>2012-11-11</pubdate>
</book>
</booklist>
- 解析XML文件
方法:
minidom.parse(filename):加载读取XML文件
doc.documentElement:获取XML文档对象
node.getAttribute(AttributeName):获取XML节点属性值
node.getElementsByTagName(TagName):获取XML节点对象集合
node.childNodes :返回子节点列表。
node.childNodes[index].nodeValue:获取XML节点值
node.firstChild:访问第一个节点,等价于pagexml.childNodes[0]
返回Node节点的xml表示的文本:
doc = minidom.parse(filename)
doc.toxml('UTF-8')
访问元素属性:
Node.attributes["id"]
a.name #就是上面的 "id"
a.value #属性的值
举例一:
XML文件:
XML文件:
<?xml version="1.0" encoding="UTF-8"?>
<users>1
<user id="">
<username>Admin</username>
<email>admin@live.cn</email>
<age>23</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin2</username>
<email>admin2@live.cn</email>
<age>22</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin3</username>
<email>admin3@live.cn</email>
<age>27</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin4</username>
<email>admin4@live.cn</email>
<age>25</age>
<sex>女</sex>
</user>
<user id="">
<username>Admin5</username>
<email>admin5@live.cn</email>
<age>20</age>
<sex>男</sex>
</user>
<user id="">
<username>Admin6</username>
<email>admin6@live.cn</email>
<age>23</age>
<sex>女</sex>
</user>
</users>
代码如下:
from xml.dom import minidom def get_attrvalue(node, attrname):
return node.getAttribute(attrname) if node else '' def get_nodevalue(node, index = 0):
return node.childNodes[index].nodeValue if node else '' def get_xmlnode(node,name):
return node.getElementsByTagName(name) if node else [] def xml_to_string(filename='D:\PycharmProjects\untitled\wxfrom\user.xml'):
doc = minidom.parse(filename)
return doc.toxml('UTF-8') def get_xml_data(filename='user.xml'):
doc = minidom.parse(filename)
root = doc.documentElement user_nodes = get_xmlnode(root,'user')
user_list=[]
for node in user_nodes:
user_id = get_attrvalue(node,'id')
node_name = get_xmlnode(node,'username')
node_email = get_xmlnode(node,'email')
node_age = get_xmlnode(node,'age')
node_sex = get_xmlnode(node,'sex') user_name =get_nodevalue(node_name[0]).encode('utf-8','ignore')
user_email = get_nodevalue(node_email[0]).encode('utf-8','ignore')
user_age = int(get_nodevalue(node_age[0]))
user_sex = get_nodevalue(node_sex[0]).encode('utf-8','ignore')
user = {}
user['id'] , user['username'] , user['email'] , user['age'] , user['sex'] = (
int(user_id), user_name , user_email , user_age , user_sex
)
user_list.append(user)
return user_list def test_xmltostring():
print xml_to_string() def test_laod_xml():
user_list = get_xml_data()
for user in user_list :
#print user['sex']
print '-----------------------------------------------------'
if user:
user_str='编 号:%d\n用户名:%s\n性 别:%s\n年 龄:%s\n邮 箱:%s\n ' % (int(user['id']) , user['username'], user['sex'] , user['age'] , user['email'])
print user_str
print '=====================================================' if __name__ == "__main__":
test_xmltostring() # 打印输出XML文件
test_laod_xml() # 解析读取数据
解析运行结果如下:
解析输出结果:
-----------------------------------------------------
编 号:1000001
用户名:Admin
性 别:男
年 龄:23
邮 箱:admin@live.cn
=====================================================
-----------------------------------------------------
编 号:1000002
用户名:Admin2
性 别:男
年 龄:22
邮 箱:admin2@live.cn
=====================================================
-----------------------------------------------------
编 号:1000003
用户名:Admin3
性 别:男
年 龄:27
邮 箱:admin3@live.cn
=====================================================
-----------------------------------------------------
编 号:1000004
用户名:Admin4
性 别:女
年 龄:25
邮 箱:admin4@live.cn
=====================================================
-----------------------------------------------------
编 号:1000005
用户名:Admin5
性 别:男
年 龄:20
邮 箱:admin5@live.cn
=====================================================
-----------------------------------------------------
编 号:1000006
用户名:Admin6
性 别:女
年 龄:23
邮 箱:admin6@live.cn
=====================================================
举例二:
XML文件:
<?xml version="1.0" ?>
<!--This is a simple xml.-->
<booklist>
<book id="">
<title>An apple</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Zhang</lastname>
</name>
</author>
<pubdate>2012-1-12</pubdate>
</book> <book id="">
<title>Love</title>
<author>
<name>
<firstname>Mike</firstname>
<lastname>Li</lastname>
</name>
</author>
<pubdate>2012-1-10</pubdate>
</book> <book id="">
<title>Steve.Jobs</title>
<author>
<name>
<firstname>Tom</firstname>
<lastname>Wang</lastname>
</name>
</author>
<pubdate>2012-1-19</pubdate>
</book> <book id="">
<title>Harry Potter</title>
<author>
<name>
<firstname>Peter</firstname>
<lastname>Chen</lastname>
</name>
</author>
<pubdate>2012-11-11</pubdate>
</book>
</booklist>
代码如下:
from xml.dom import minidom,Node class bookscanner:
def __init__(self,doc):
for child in doc.childNodes :
if child.nodeType == Node.ELEMENT_NODE and child.tagName == "book" :
bookid = child.getAttribute("id")
print "*"*20
print "Book id : " , bookid
self.handle_book(child) def handle_book(self,node):
for child in node.childNodes :
if child.nodeType == Node.ELEMENT_NODE :
if child.tagName == "title":
print "Title : " , self.getText(child.firstChild)
if child.tagName == "author":
self.handle_author(child)
if child.tagName == "pubdate":
print "Pubdate : " , self.getText(child.firstChild) def getText(self,node):
if node.nodeType == Node.TEXT_NODE :
return node.nodeValue
else: return "" def handle_author(self,node):
author = node.firstChild
for child in author.childNodes:
if child.nodeType == Node.ELEMENT_NODE:
if child.tagName == "firstname" :
print "Firstname : ", self.getText(child.firstChild)
if child.tagName == "lastname" :
print "Lastname : " , self.getText(child.firstChild) doc = minidom.parse("D:\PycharmProjects\untitled\wxfrom\\book.xml")
for child in doc.childNodes :
if child.nodeType == Node.COMMENT_NODE:
print "Conment : " , child.nodeValue
if child.nodeType == Node.ELEMENT_NODE:
bookscanner(child)
解析运行结果如下:
Conment : This is a simple xml.
********************
Book id : 1001
Title : An apple
Pubdate : 2012-1-12
********************
Book id : 1002
Title : Love
Pubdate : 2012-1-10
********************
Book id : 1003
Title : Steve.Jobs
Pubdate : 2012-1-19
********************
Book id : 1004
Title : Harry Potter
Pubdate : 2012-11-11
python_day6学习笔记的更多相关文章
- js学习笔记:webpack基础入门(一)
之前听说过webpack,今天想正式的接触一下,先跟着webpack的官方用户指南走: 在这里有: 如何安装webpack 如何使用webpack 如何使用loader 如何使用webpack的开发者 ...
- PHP-自定义模板-学习笔记
1. 开始 这几天,看了李炎恢老师的<PHP第二季度视频>中的“章节7:创建TPL自定义模板”,做一个学习笔记,通过绘制架构图.UML类图和思维导图,来对加深理解. 2. 整体架构图 ...
- PHP-会员登录与注册例子解析-学习笔记
1.开始 最近开始学习李炎恢老师的<PHP第二季度视频>中的“章节5:使用OOP注册会员”,做一个学习笔记,通过绘制基本页面流程和UML类图,来对加深理解. 2.基本页面流程 3.通过UM ...
- 2014年暑假c#学习笔记目录
2014年暑假c#学习笔记 一.C#编程基础 1. c#编程基础之枚举 2. c#编程基础之函数可变参数 3. c#编程基础之字符串基础 4. c#编程基础之字符串函数 5.c#编程基础之ref.ou ...
- JAVA GUI编程学习笔记目录
2014年暑假JAVA GUI编程学习笔记目录 1.JAVA之GUI编程概述 2.JAVA之GUI编程布局 3.JAVA之GUI编程Frame窗口 4.JAVA之GUI编程事件监听机制 5.JAVA之 ...
- seaJs学习笔记2 – seaJs组建库的使用
原文地址:seaJs学习笔记2 – seaJs组建库的使用 我觉得学习新东西并不是会使用它就够了的,会使用仅仅代表你看懂了,理解了,二不代表你深入了,彻悟了它的精髓. 所以不断的学习将是源源不断. 最 ...
- CSS学习笔记
CSS学习笔记 2016年12月15日整理 CSS基础 Chapter1 在console输入escape("宋体") ENTER 就会出现unicode编码 显示"%u ...
- HTML学习笔记
HTML学习笔记 2016年12月15日整理 Chapter1 URL(scheme://host.domain:port/path/filename) scheme: 定义因特网服务的类型,常见的为 ...
- DirectX Graphics Infrastructure(DXGI):最佳范例 学习笔记
今天要学习的这篇文章写的算是比较早的了,大概在DX11时代就写好了,当时龙书11版看得很潦草,并没有注意这篇文章,现在看12,觉得是跳不过去的一篇文章,地址如下: https://msdn.micro ...
随机推荐
- BZOJ1040:[ZJOI2008]骑士——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=1040 题面大意:n个人有一个价值和一个最恨的人,现在组出一个队伍使得价值最大且没有仇恨关系. ——— ...
- BZOJ1046 [HAOI2007]上升序列 【LIS + 字典序最小】
1046: [HAOI2007]上升序列 Time Limit: 10 Sec Memory Limit: 162 MB Submit: 5410 Solved: 1877 [Submit][St ...
- App.config的典型应用
----.net中XML的典型应用 第一种修改方式: 添加xml节点figguration内容, 微软提供了一种方案来读取connectionStrings里的内容 这样就可以拿到连接sql serv ...
- PHP导出excel,无乱码
php部分 header("Content-type:application/octet-stream"); header("Accept-Ranges:bytes&qu ...
- JS中验证URL、图片
//验证URL function IsURL (str_url) { var strRegex = '^((https|http|ftp|rtsp|mms)?://)' + '?(([0-9a-z_! ...
- 一款基础模型的JS打飞机游戏特效代码
<!DOCTYPE html> <html lang="en"> <head> <title>一款基础模型的JS打飞机游戏特效代码& ...
- (转)关于block使用的5点注意事项
1.在使用block前需要对block指针做判空处理. 不判空直接使用,一旦指针为空直接产生崩溃. if (!self.isOnlyNet) { if (succBlock == NULL) { // ...
- tcpdump抓取ftp密码
步骤: 1.登陆ftp服务器,执行命令: tcpdump -i wlan0 -w password.bin -c 500 port 21 2.有人登陆后,执行: tcpdump -v -XX -r p ...
- POJ1015 DP
Jury Compromise Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 28927 Accepted: 7676 ...
- 2015/8/29 Python基础(3):数值
数字提供了标量储存和直接访问,是不可更改类型,每次变更数值会产生新的对象.Python支持多种数字类型,包括整型.长整型.布尔型.双精度浮点.十进制浮点和复数.在Python中,变量并不是一个盒子,而 ...