• python_day6学习笔记


    一、Logger模块

    • logging.basicConfig函数
     1 可通过具体参数来更改logging模块默认行为,可用参数有
     2 filename:   用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
     3 filemode:   文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
     4 format:     指定handler使用的日志显示格式。
     5 datefmt:    指定日期时间格式。
     6 level:      设置rootlogger的日志级别
     7 stream:     用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
     8 日志级别等级CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
     9 
    10 format参数中可能用到的格式化串:
    11 %(name)s          Logger的名字
    12 %(levelno)s       数字形式的日志级别
    13 %(levelname)s     文本形式的日志级别
    14 %(pathname)s      调用日志输出函数的模块的完整路径名,可能没有
    15 %(filename)s      调用日志输出函数的模块的文件名
    16 %(module)s        调用日志输出函数的模块名
    17 %(funcName)s      调用日志输出函数的函数名
    18 %(lineno)d        调用日志输出函数的语句所在的代码行
    19 %(created)f          当前时间,用UNIX标准的表示时间的浮 点数表示
    20 %(relativeCreated)d  输出日志信息时的,自Logger创建以 来的毫秒数
    21 %(asctime)s          字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
    22 %(thread)d           线程ID。可能没有
    23 %(threadName)s       线程名。可能没有
    24 %(process)d          进程ID。可能没有
    25 %(message)s          用户输出的消

     举例:

     1 import logging
     2 logging.basicConfig(level=logging.DEBUG,
     3                 format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
     4                 datefmt='%Y-%m-%d %H:%M:%S',
     5                 filename='myapp.log',
     6                 filemode='w')
     7 
     8 logging.debug('This is debug message')
     9 logging.info('This is info message')
    10 logging.warning('This is warning message')
    11 logging.error('error message')
    12 logging.critical('critical message')

    结果:

    1  [root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:13] DEBUG   : This is debug message
    2  [root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:14] INFO    : This is info message
    3  [root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:15] WARNING : This is warning message
    4  [root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:16] ERROR   : error message
    5  [root]:[2015-07-03 13:37:40] [test12.py|<module>] [line:17] CRITICAL: critical message
     1 logging分为4个模块: loggers, handlers, filters, and formatters
     2 ● loggers: 提供应用程序调用的接口
     3 ● handlers: 把日志发送到指定的位置
     4 ● filters: 过滤日志信息
     5 ● formatters: 格式化输出日志
     6 Logger
     7 Logger.setLevel() 设置日志级别 
     8 Logger.addHandler()和Logger.removeHandler() 增加和删除日志处理器 
     9 Logger.addFilter()和Logger.removeFilter() 增加和删除过滤器 
    10 Logger.debug(), Logger.info(), Logger.warning(), Logger.error(), and Logger.critical() 创建不同的级别的日志 
    11 getLogger() 获取日志的根实例
    12 Handler
    13 setLevel() 设置日志级别 
    14 setFormatter() 设置输出格式 
    15 addFilter() and removeFilter() 增加和删除过滤器
    16 Formatter
    17 默认形式为: %Y-%m-%d %H:%M:%S. 
    18 格式为: %()s
    • logging.getLogger函数
     1 import logging
     2 log = logging.getLogger('yinjia')
     3 logging.basicConfig(level=logging.DEBUG,
     4                 format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
     5                 datefmt='%Y-%m-%d %H:%M:%S',
     6                 filename='myapp.log',
     7                 filemode='w')
     8 
     9 log.debug('This is debug message')
    10 log.info('This is info message')
    11 log.warning('This is warning message')
    12 log.error('error message')
    13 log.critical('critical message')
    14  输出结果:
    15  [yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:12] DEBUG   : This is debug message
    16  [yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:13] INFO    : This is info message
    17  [yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:14] WARNING : This is warning message
    18  [yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:15] ERROR   : error message
    19  [yinjia]:[2015-07-03 14:14:07] [test12.py|<module>] [line:16] CRITICAL: critical message
    20  返回一个logger对象,如果没有指定名字将返回root logger
    • logging.getLogger函数

    以ERROR级别记录日志消息,异常跟踪信息将被自动添加到日志消息里。Logger.exception通过用在异常处理块中,例如:

     1 import logging
     2 log = logging.getLogger('yinjia')
     3 logging.basicConfig(level=logging.DEBUG,
     4                 format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
     5                 datefmt='%Y-%m-%d %H:%M:%S',
     6                 filename='myapp.log',
     7                 filemode='w')
     8 
     9 try:
    10     raise Exception,'This is a exception'
    11 except:
    12     log.exception('This is debug message') #异常信息被自动添加到日志消息中
    13 
    14  输出结果:
    15  [yinjia]:[2015-07-03 14:24:43] [test12.py|<module>] [line:15] ERROR   : This is debug message
    16  Traceback (most recent call last):
    17    File "D:/PycharmProjects/untitled/test12.py", line 13, in <module>
    18      raise Exception,'This is a exception'
    19  Exception: This is a exception
    • 其它函数
     1 import logging
     2 log = logging.getLogger('yinjia')
     3 logging.basicConfig(level=logging.DEBUG,
     4                 format='[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s',
     5                 datefmt='%Y-%m-%d %H:%M:%S',
     6                 filename='myapp.log',
     7                 filemode='w')
     8 
     9 # 再创建一个handler,用于输出到控制台
    10 console = logging.StreamHandler()
    11 # 定义handler的输出格式formatter
    12 console.setLevel(logging.INFO)
    13 formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    14 console.setFormatter(formatter)
    15 # 给logging添加handler
    16 logging.getLogger('').addHandler(console)
    17 logging.info('Jackdaws love my big sphinx of quartz.')
    18 
    19 log.debug('This is debug message')
    20 log.info('This is info message')
    21 log.warning('This is warning message')
    22 log.error('error message')
    23 log.critical('critical message')
    24 
    25  控制台输出结果:
    26  root        : INFO     Jackdaws love my big sphinx of quartz.
    27  yinjia      : INFO     This is info message
    28  yinjia      : WARNING  This is warning message
    29  yinjia      : ERROR    error message
    30  yinjia      : CRITICAL critical message
    31  文件输出结果同上例,只多了一行root用户记录。

    另一种方法举例:

     1 import logging
     2 # 创建一个logger
     3 logger = logging.getLogger('yinjia')
     4 logger.setLevel(logging.DEBUG)
     5 
     6 format = '[%(name)s]:[%(asctime)s] [%(filename)s|%(funcName)s] [line:%(lineno)d] %(levelname)-8s: %(message)s'
     7 fmt = '[%(asctime)-12s] [%(filename)s][line:%(lineno)d] [%(levelname)8s]: %(message)s'
     8 
     9 # 创建一个handler,用于输出到控制台
    10 console = logging.StreamHandler()
    11 
    12 # 创建一个handler,用于写入日志文件
    13 fp = logging.FileHandler('D:PycharmProjectsuntitledmyapp.log')
    14 
    15 # 定义handler的输出格式formatter
    16 formatter = logging.Formatter(fmt)
    17 fpmatter = logging.Formatter(format)
    18 console.setFormatter(formatter)
    19 fp.setFormatter(fpmatter)
    20 
    21 # 给logging添加handler
    22 logger.addHandler(console)
    23 logger.addHandler(fp)
    24 
    25 # 记录日志
    26 logger.debug('This is debug message')
    27 logger.info('This is info message')
    28 logger.warning('This is warning message')
    29 logger.error('error message')
    30 logger.critical('critical message')
    31  以上可以同时输出到控制台和LOG日志文件。
    32  流程:创建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即为当前要添加的节点了。

    举例如下:

     1 from xml.dom import minidom
     2 import os
     3 import os.path
     4 
     5 filename = os.getcwd() + os.path.sep
     6 print filename
     7 
     8 doc = minidom.Document()
     9 doc.appendChild(doc.createComment("This is a simple xml."))
    10 booklist = doc.createElement("booklist")
    11 doc.appendChild(booklist)
    12 
    13 def addBook(newbook):
    14     book = doc.createElement("book")
    15     book.setAttribute("id",newbook["id"])
    16 
    17     title = doc.createElement("title")
    18     title.appendChild(doc.createTextNode(newbook["title"]))
    19     book.appendChild(title)
    20 
    21     author = doc.createElement("author")
    22     name = doc.createElement("name")
    23     firstname = doc.createElement("firstname")
    24     firstname.appendChild(doc.createTextNode(newbook["firstname"]))
    25     lastname = doc.createElement("lastname")
    26     lastname.appendChild(doc.createTextNode(newbook["lastname"]))
    27     name.appendChild(firstname)
    28     name.appendChild(lastname)
    29     author.appendChild(name)
    30     book.appendChild(author)
    31 
    32     pubdate = doc.createElement("pubdate")
    33     pubdate.appendChild(doc.createTextNode(newbook["pubdate"]))
    34     book.appendChild(pubdate)
    35 
    36     booklist.appendChild(book)
    37 
    38 addBook({"id":"1001","title":"An apple","firstname":"Peter","lastname":"Zhang","pubdate":"2012-1-12"})
    39 addBook({"id":"1002","title":"Love","firstname":"Mike","lastname":"Li","pubdate":"2012-1-10"})
    40 addBook({"id":"1003","title":"Steve.Jobs","firstname":"Tom","lastname":"Wang","pubdate":"2012-1-19"})
    41 addBook({"id":"1004","title":"Harry Potter","firstname":"Peter","lastname":"Chen","pubdate":"2012-11-11"})
    42 
    43 f = file(filename + "book.xml","w")
    44 doc.writexml(f)
    45 f.close()
    View Code

    运行结果如下:

     1 生成XML文件如下:
     2  <?xml version="1.0" ?>
     3  <!--This is a simple xml.-->
     4  <booklist>
     5  <book id="1001">
     6     <title>An apple</title>
     7  <author>
     8      <name>
     9        <firstname>Peter</firstname>
    10        <lastname>Zhang</lastname>
    11      </name>
    12  </author>
    13  <pubdate>2012-1-12</pubdate>
    14  </book>
    15  
    16  <book id="1002">
    17    <title>Love</title>
    18  <author>
    19    <name>
    20      <firstname>Mike</firstname>
    21      <lastname>Li</lastname>
    22     </name>
    23  </author>
    24  <pubdate>2012-1-10</pubdate>
    25  </book>
    26  
    27  <book id="1003">
    28    <title>Steve.Jobs</title>
    29  <author>
    30    <name>
    31     <firstname>Tom</firstname>
    32     <lastname>Wang</lastname>
    33    </name>
    34  </author>
    35  <pubdate>2012-1-19</pubdate>
    36  </book>
    37  
    38  <book id="1004">
    39    <title>Harry Potter</title>
    40  <author>
    41    <name>
    42      <firstname>Peter</firstname>
    43      <lastname>Chen</lastname>
    44    </name>
    45  </author>
    46  <pubdate>2012-11-11</pubdate>
    47  </book>
    48  </booklist>
    View Code
    • 解析XML文件
     1  方法:
     2  minidom.parse(filename):加载读取XML文件
     3  doc.documentElement:获取XML文档对象
     4  node.getAttribute(AttributeName):获取XML节点属性值
     5  node.getElementsByTagName(TagName):获取XML节点对象集合
     6  node.childNodes :返回子节点列表。
     7  node.childNodes[index].nodeValue:获取XML节点值
     8  node.firstChild:访问第一个节点,等价于pagexml.childNodes[0]
     9  返回Node节点的xml表示的文本:
    10  doc = minidom.parse(filename)
    11  doc.toxml('UTF-8')
    12  访问元素属性:
    13  Node.attributes["id"] 
    14  a.name #就是上面的 "id" 
    15  a.value #属性的值

    举例一:

    XML文件:

     1  XML文件:
     2  <?xml version="1.0" encoding="UTF-8"?>
     3  <users>1
     4      <user id="1000001">
     5          <username>Admin</username>
     6          <email>admin@live.cn</email>
     7          <age>23</age>
     8          <sex>男</sex>
     9      </user>
    10      <user id="1000002">
    11          <username>Admin2</username>
    12          <email>admin2@live.cn</email>
    13          <age>22</age>
    14          <sex>男</sex>
    15      </user>
    16      <user id="1000003">
    17          <username>Admin3</username>
    18          <email>admin3@live.cn</email>
    19          <age>27</age>
    20          <sex>男</sex>
    21      </user>
    22      <user id="1000004">
    23          <username>Admin4</username>
    24          <email>admin4@live.cn</email>
    25          <age>25</age>
    26          <sex>女</sex>
    27      </user>
    28      <user id="1000005">
    29          <username>Admin5</username>
    30          <email>admin5@live.cn</email>
    31          <age>20</age>
    32          <sex>男</sex>
    33      </user>
    34      <user id="1000006">
    35          <username>Admin6</username>
    36          <email>admin6@live.cn</email>
    37          <age>23</age>
    38          <sex>女</sex>
    39      </user>
    40  </users>
    View Code

    代码如下:

     1 from  xml.dom import  minidom
     2 
     3 
     4 def get_attrvalue(node, attrname):
     5      return node.getAttribute(attrname) if node else ''
     6 
     7 def get_nodevalue(node, index = 0):
     8     return node.childNodes[index].nodeValue if node else ''
     9 
    10 def get_xmlnode(node,name):
    11     return node.getElementsByTagName(name) if node else []
    12 
    13 def xml_to_string(filename='D:PycharmProjectsuntitledwxfromuser.xml'):
    14     doc = minidom.parse(filename)
    15     return doc.toxml('UTF-8')
    16 
    17 def get_xml_data(filename='user.xml'):
    18     doc = minidom.parse(filename)
    19     root = doc.documentElement
    20 
    21     user_nodes = get_xmlnode(root,'user')
    22     user_list=[]
    23     for node in user_nodes:
    24         user_id = get_attrvalue(node,'id')
    25         node_name = get_xmlnode(node,'username')
    26         node_email = get_xmlnode(node,'email')
    27         node_age = get_xmlnode(node,'age')
    28         node_sex = get_xmlnode(node,'sex')
    29 
    30         user_name =get_nodevalue(node_name[0]).encode('utf-8','ignore')
    31         user_email = get_nodevalue(node_email[0]).encode('utf-8','ignore')
    32         user_age = int(get_nodevalue(node_age[0]))
    33         user_sex = get_nodevalue(node_sex[0]).encode('utf-8','ignore')
    34         user = {}
    35         user['id'] , user['username'] , user['email'] , user['age'] , user['sex'] = (
    36             int(user_id), user_name , user_email , user_age , user_sex
    37         )
    38         user_list.append(user)
    39     return user_list
    40 
    41 def test_xmltostring():
    42     print xml_to_string()
    43 
    44 def test_laod_xml():
    45     user_list = get_xml_data()
    46     for user in user_list :
    47         #print user['sex']
    48         print '-----------------------------------------------------'
    49         if user:
    50             user_str='编   号:%d
    用户名:%s
    性   别:%s
    年   龄:%s
    邮   箱:%s
     ' % (int(user['id']) , user['username'], user['sex'] , user['age'] , user['email'])
    51             print user_str
    52             print '====================================================='
    53 
    54 if __name__ == "__main__":
    55     test_xmltostring()  # 打印输出XML文件
    56     test_laod_xml()  # 解析读取数据
    View Code

    解析运行结果如下:

     解析输出结果:
     -----------------------------------------------------
     编   号: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
      =====================================================
    View Code

    举例二:

    XML文件:

     1  <?xml version="1.0" ?>
     2  <!--This is a simple xml.-->
     3  <booklist>
     4  <book id="1001">
     5     <title>An apple</title>
     6  <author>
     7      <name>
     8        <firstname>Peter</firstname>
     9        <lastname>Zhang</lastname>
    10      </name>
    11  </author>
    12  <pubdate>2012-1-12</pubdate>
    13  </book>
    14  
    15  <book id="1002">
    16    <title>Love</title>
    17  <author>
    18    <name>
    19      <firstname>Mike</firstname>
    20      <lastname>Li</lastname>
    21     </name>
    22  </author>
    23  <pubdate>2012-1-10</pubdate>
    24  </book>
    25  
    26  <book id="1003">
    27    <title>Steve.Jobs</title>
    28  <author>
    29    <name>
    30     <firstname>Tom</firstname>
    31     <lastname>Wang</lastname>
    32    </name>
    33  </author>
    34  <pubdate>2012-1-19</pubdate>
    35  </book>
    36  
    37  <book id="1004">
    38    <title>Harry Potter</title>
    39  <author>
    40    <name>
    41      <firstname>Peter</firstname>
    42      <lastname>Chen</lastname>
    43    </name>
    44  </author>
    45  <pubdate>2012-11-11</pubdate>
    46  </book>
    47  </booklist>
    View Code

    代码如下:

     1 from xml.dom import minidom,Node
     2 
     3 class bookscanner:
     4     def __init__(self,doc):
     5         for child in doc.childNodes :
     6             if child.nodeType == Node.ELEMENT_NODE and child.tagName == "book" :
     7                 bookid = child.getAttribute("id")
     8                 print "*"*20
     9                 print "Book id : " , bookid
    10                 self.handle_book(child)
    11 
    12     def handle_book(self,node):
    13         for child in node.childNodes :
    14             if child.nodeType == Node.ELEMENT_NODE :
    15                 if child.tagName == "title":
    16                     print "Title : " , self.getText(child.firstChild)
    17                 if child.tagName == "author":
    18                     self.handle_author(child)
    19                 if child.tagName == "pubdate":
    20                     print "Pubdate : " , self.getText(child.firstChild)
    21 
    22     def getText(self,node):
    23         if node.nodeType == Node.TEXT_NODE :
    24             return node.nodeValue
    25         else: return ""
    26 
    27     def handle_author(self,node):
    28         author = node.firstChild
    29         for child in author.childNodes:
    30             if child.nodeType == Node.ELEMENT_NODE:
    31                 if child.tagName == "firstname" :
    32                     print "Firstname : ", self.getText(child.firstChild)
    33                 if child.tagName == "lastname" :
    34                     print "Lastname : " , self.getText(child.firstChild)
    35 
    36 doc = minidom.parse("D:PycharmProjectsuntitledwxfrom\book.xml")
    37 for child in doc.childNodes :
    38     if child.nodeType == Node.COMMENT_NODE:
    39         print "Conment : " , child.nodeValue
    40     if child.nodeType == Node.ELEMENT_NODE:
    41         bookscanner(child)
    42  
    View Code

    解析运行结果如下:

     1  Conment :  This is a simple xml.
     2  ********************
     3  Book id :  1001
     4  Title :  An apple
     5  Pubdate :  2012-1-12
     6  ********************
     7  Book id :  1002
     8  Title :  Love
     9  Pubdate :  2012-1-10
    10  ********************
    11  Book id :  1003
    12  Title :  Steve.Jobs
    13  Pubdate :  2012-1-19
    14  ********************
    15  Book id :  1004
    16  Title :  Harry Potter
    17  Pubdate :  2012-11-11
    View Code
  • 相关阅读:
    从零搭建springboot+mybatis逆向工程
    基础SQL总结
    Map集合浅谈
    ArrayList、LinkedList与Vector的区别
    java多线程总结
    P4108 [HEOI2015]公约数数列
    P2168 [NOI2015] 荷马史诗
    正睿 2021 Noip 十连测 Day2
    CF772E Verifying Kingdom
    BZOJ1767 [CEOI2009] Harbingers
  • 原文地址:https://www.cnblogs.com/yinjia/p/5596950.html
Copyright © 2020-2023  润新知