zoukankan      html  css  js  c++  java
  • Python全栈开发,Day6

    本章内容

    1.  模块介绍
    2. time&datetime
    3. random
    4. os
    5. sys
    6. shutil
    7. shelve
    8. xml处理
    9. yaml处理
    10. configparser
    11. hashlib
    12. subprocess
    13. logging

    一、模块介绍

    模块,用一坨代码实现某个功能的代码集合。

    类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来说,肯呢个需要多个函数才能完成(函数又可以在不同的.py文件中),n个.py文件组成的代码集合就称为模块。

     

    如:os是系统相关的模块;file是文件操作相关的模块。

    模块分为三种:

    • 自定义模块
    • 内置标准模块(又称标准库)
    • 开源模块

      自定义模块和开源模块的使用参考,点击

     

      导入模块:

      python之所以应用越来越广泛,在一定程度上也依赖程度上也依赖于其为程序员提供了大量的模块以供使用,如果想要使用模块,则需要导入。导入模块有以下几种方法:

     

    1 import module
    2 from module.xx xx import xx
    3 from module.xx xx import xx as rename
    4 from module.xx xx import *

    二、time&datatime

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # Author:Lyon
     4 
     5 import time
     6 
     7 #返回处理器时间,3.3开始已废弃,改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
     8 print(time.clock())
     9 
    10 #返回与utc时间的时间差,以秒计算
    11 print(time.altzone)
    12 
    13 #返回时间格式"Fri Aug 19 11:14:16 2016"
    14 print(time.asctime())
    15 
    16 #返回本地时间的struct time对象格式
    17 print(time.localtime())
    18 
    19 #返回utc时间的struc时间对象格式
    20 print(time.gmtime(time.time()-800000))
    21 
    22 #返回时间格式"Fri Aug 19 11:14:16"
    23 print(time.asctime(time.localtime()))
    24 
    25 #返回Fri Aug 19 12:38:29 2016 格式,同上
    26 print(time.ctime())
    27 
    28 #日期字符串转成时间戳
    29 #将日期字符串转成struct时间对象格式
    30 string_2_struct = time.strptime("2016/05/22","%Y/%m/%d")
    31 print(string_2_struct)
    32 
    33 #将struct时间对象转成时间戳
    34 struct_2_stamp = time.mktime(string_2_struct)
    35 print(struct_2_stamp)
    36 
    37 #将时间戳转为字符串格式
    38 #将utc时间戳转换成struct_time格式
    39 print(time.gmtime(time.time()-86640))
    40 
    41 #将utc struct_time格式转成指定的字符串格式
    42 print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()))
    43 
    44 #时间加减detatime
    45 import datetime
    46 #返回 2017-03-13 13:12:41.485237
    47 print(datetime.datetime.now())
    48 
    49 #时间戳直接转成日期格式2017-03-13
    50 print(datetime.date.fromtimestamp(time.time()))
    51 
    52 print(datetime.datetime.now())
    53 #当前时间+3天
    54 print(datetime.datetime.now()+datetime.timedelta(3))
    55 #当前时间-3天
    56 print(datetime.datetime.now()+datetime.timedelta(-3))
    57 #当前时间+3小时
    58 print(datetime.datetime.now()+datetime.timedelta(hours=3))
    59 #当前时间+30分钟
    60 print(datetime.datetime.now()+datetime.timedelta(minutes=30))
    61 
    62 #时间替换
    63 c_time = datetime.datetime.now()
    64 print(c_time.replace(minute=2,hour=2))
    DirectiveMeaningNotes
    %a Locale’s abbreviated weekday name.  
    %A Locale’s full weekday name.  
    %b Locale’s abbreviated month name.  
    %B Locale’s full month name.  
    %c Locale’s appropriate date and time representation.  
    %d Day of the month as a decimal number [01,31].  
    %H Hour (24-hour clock) as a decimal number [00,23].  
    %I Hour (12-hour clock) as a decimal number [01,12].  
    %j Day of the year as a decimal number [001,366].  
    %m Month as a decimal number [01,12].  
    %M Minute as a decimal number [00,59].  
    %p Locale’s equivalent of either AM or PM. (1)
    %S Second as a decimal number [00,61]. (2)
    %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
    %w Weekday as a decimal number [0(Sunday),6].  
    %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
    %x Locale’s appropriate date representation.  
    %X Locale’s appropriate time representation.  
    %y Year without century as a decimal number [00,99].  
    %Y Year with century as a decimal number.  
    %z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
    %Z Time zone name (no characters if no time zone exists).  
    %% A literal '%' character.  

    三、random

    随机数

    1 import random
    2 #生成一个0到1的随机浮点数:0 < = n < 1.0
    3 print(random.random())
    4 #生成一个1到2范围内的随机整数,1是下限,2是上限
    5 print(random.randint(1,2))
    6 #生成0到100之间的偶数
    7 print(random.randrange(0,101,2))
    8 #生成一个随机字符
    9 print(random.choice('abcdefgh'))

     

    生成随机验证码

     1 import random
     2 #创建一个空字符串
     3 checkcode = ''
     4 #四位的随机数
     5 for i in range(4):
     6     current = random.randrange(0,4)
     7     #生成的随机数与i相等则匹配字母
     8     if i == current:
     9         #chr 返回整数所对应的ASCII码,65-90为大写字母
    10         tmp = chr(random.randint(65,90))
    11     #不想到等就匹配数字
    12     else:
    13         #生成一个0到9之间的随机数
    14         tmp = random.randrange(0,9)
    15     #将匹配到的字符添加进字符串里
    16     checkcode += str(tmp)
    17 #打印所生成的随机数
    18 print(checkcode)

    更多random的用法,猛戳这里

    四、os

    提供对操作系统进行调用的接口

     1 import os
     2 
     3 os.getcwd() #获取当前工作目录,即当前python脚本工作的目录路径
     4 os.chdir("dirname")  #改变当前脚本工作目录;相当于shell下cd
     5 os.curdir  #返回当前目录: ('.')
     6 os.pardir  #获取当前目录的父目录字符串名:('..')
     7 os.makedirs('dirname1/dirname2')    #可生成多层递归目录
     8 os.removedirs('dirname1')    #若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
     9 os.mkdir('dirname')   # 生成单级目录;相当于shell中mkdir dirname
    10 os.rmdir('dirname')   # 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    11 os.listdir('dirname')   # 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    12 os.remove()  #删除一个文件
    13 os.rename("oldname","newname")  #重命名文件/目录
    14 os.stat('path/filename')  #获取文件/目录信息
    15 os.sep    #输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    16 os.linesep    #输出当前平台使用的行终止符,win下为"	
    ",Linux下为"
    "
    17 os.pathsep    #输出用于分割文件路径的字符串
    18 os.name    #输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    19 os.system("bash command")  #运行shell命令,直接显示
    20 os.environ # 获取系统环境变量
    21 os.path.abspath(path='')  #返回path规范化的绝对路径
    22 os.path.split(path='')  #将path分割成目录和文件名二元组返回
    23 os.path.dirname(path='') # 返回path的目录。其实就是os.path.split(path)的第一个元素
    24 os.path.basename(path='') # 返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    25 os.path.exists(path='') # 如果path存在,返回True;如果path不存在,返回False
    26 os.path.isabs(path='')  #如果path是绝对路径,返回True
    27 os.path.isfile(path='')  #如果path是一个存在的文件,返回True。否则返回False
    28 os.path.isdir(path='')  #如果path是一个存在的目录,则返回True。否则返回False
    29 os.path.join(path1[, path2[, ...]])  #将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    30 os.path.getatime(path='')  #返回path所指向的文件或者目录的最后存取时间
    31 os.path.getmtime(path='')  #返回path所指向的文件或者目录的最后修改时间

    五、sys

    用于提供对解释器相关的操作

    1 sys.argv          # 命令行参数List,第一个元素是程序本身路径
    2 sys.exit(n)        #退出程序,正常退出时exit(0)
    3 sys.version     #获取Python解释程序的版本信息
    4 sys.maxint        # 最大的Int值
    5 sys.path          # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    6 sys.platform      # 返回操作系统平台名称
    7 sys.stdout.write('please:')
    8 val = sys.stdin.readline()[:-1]

    六、shutil

     高级的文件、文件夹、压缩包处理模块

     1 import shutil
     2 #将文件内容拷贝到另一个文件中,可以部分内容从fsrc到fdst
     3 shutil.copyfileobj(fsrc,fdst,[,length])
     4 #拷贝文件
     5 shutil.copyfile(src,dst)
     6 #仅拷贝权限。内容、组、用户均不变
     7 shutil.copymode(src,dst)
     8 #拷贝状态的信息,包括:mode bits,atime,mtime,flags
     9 shutil.copystsat(src,dst)
    10 #拷贝文件和权限
    11 shutil.copy(src,dst)
    12 #拷贝文件和状态信息
    13 shutil.copy2(src,dst)
    14 #递归的去拷贝文件
    15 shutil.ignore_patterns(*patterns)
    16 shutil.copytree(src, dst, symlinks=False, ignore=None)
    17 #递归的去删除文件
    18 shutil.rmtree(path[, ignore_errors[, onerror]])
    19 #递归的去移动文件
    20 shutil.move(src,dst)
    21 #创建压缩包并返回文件路经,例如:zip、tar
    22 shutil.make_archive(base_name,format,...)

     

    更多shutil相关,猛戳这里

    七、shelve

      shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以吃酒任何pickle可支持的python数据格式

     1 import shelve
     2  
     3 d = shelve.open('shelve_test') #打开一个文件
     4  
     5 class Test(object):
     6     def __init__(self,n):
     7         self.n = n
     8  
     9  
    10 t = Test(123) 
    11 t2 = Test(123334)
    12  
    13 name = ["alex","rain","test"]
    14 d["test"] = name #持久化列表
    15 d["t1"] = t      #持久化类
    16 d["t2"] = t2
    17  
    18 d.close()

    八、xml处理

    xml是实现不同语言或程序之间进行数据交换的协议,跟json差不多,但json使用起来更简单,不过古时候,在json还没诞生的黑暗年代,大家只能选择用xml呀,至今很多传统公司如金融行业很多系统的接口还主要是xml。

    xml的格式如下,就是通过<>节点来区别数据结构的

     1 <?xml version="1.0"?>
     2 <data>
     3     <country name="Liechtenstein">
     4         <rank updated="yes">2</rank>
     5         <year>2008</year>
     6         <gdppc>141100</gdppc>
     7         <neighbor name="Austria" direction="E"/>
     8         <neighbor name="Switzerland" direction="W"/>
     9     </country>
    10     <country name="Singapore">
    11         <rank updated="yes">5</rank>
    12         <year>2011</year>
    13         <gdppc>59900</gdppc>
    14         <neighbor name="Malaysia" direction="N"/>
    15     </country>
    16     <country name="Panama">
    17         <rank updated="yes">69</rank>
    18         <year>2011</year>
    19         <gdppc>13600</gdppc>
    20         <neighbor name="Costa Rica" direction="W"/>
    21         <neighbor name="Colombia" direction="E"/>
    22     </country>
    23 </data>

     

    xml协议在各个语言里都是支持的,在python中可以用一下模块操作xml

     1 import xml.etree.ElementTree as ET
     2 
     3 tree = ET.parse('xmltest.xml')
     4 root = tree.getroot()
     5 print(root.tag)
     6 
     7 #遍历xml文档
     8 for child in root:
     9     print(child.tag,child.attrib)
    10     for i in child:
    11         print(i.tag,i.text)
    12 
    13 #只遍历year节点
    14 for node in root.iter('yeat'):
    15     print(node.tag,node.text)

    九、yaml处理

    YAML是一种直观的能够被电脑识别的数据系列化格式,容易被 人们阅读,并且容易和脚本语言交互。YAML类似与XML,但是语法比XML简单得多,对于转化成数组或可以hash的数据时是很简单有效的。

    语法规则:http://pyyaml.org/

    十、confipgarser

    用于生成和修改场监配置文档,当前模块的名称在python 3.x 版本中变更为configparser

    好多软件的常见文档格式如下:

     1 [DEFAULT]
     2 ServerAliveInterval = 45
     3 Compression = yes
     4 CompressionLevel = 9
     5 ForwardX11 = yes
     6  
     7 [bitbucket.org]
     8 User = hg
     9  
    10 [topsecret.server.com]
    11 Port = 50022
    12 ForwardX11 = no

     

    如果要用python生成一个这样的文档怎么做呢?

     1 import configparser
     2 
     3 config =configparser.ConfigParser()
     4 config['DEGAULT'] = {'ServerAliveInterval':'45',
     5                      'Compression':'yes',
     6                      'CompressionLevel':'9',}
     7 config['bitbucket.org'] = {}
     8 config['bitbucket.org']['User'] = 'hg'
     9 config['topsecret.server.com'] = {}
    10 topsecret = config['topsecret.server.com']
    11 topsecret['Host Port'] = '50022'
    12 config["DEFAULT"]['Forwardx11'] = 'yes'
    13 with open('example.ini','w')as configfile:
    14     config.write(configfile)

     

    configparser增删改查语法

     1 [section1]
     2 k1 = v1
     3 k2:v2
     4   
     5 [section2]
     6 k1 = v1
     7  
     8 import ConfigParser
     9   
    10 config = ConfigParser.ConfigParser()
    11 config.read('i.cfg')
    12   
    13 # ########## 读 ##########
    14 #secs = config.sections()
    15 #print secs
    16 #options = config.options('group2')
    17 #print options
    18   
    19 #item_list = config.items('group2')
    20 #print item_list
    21   
    22 #val = config.get('group1','key')
    23 #val = config.getint('group1','key')
    24   
    25 # ########## 改写 ##########
    26 #sec = config.remove_section('group1')
    27 #config.write(open('i.cfg', "w"))
    28   
    29 #sec = config.has_section('wupeiqi')
    30 #sec = config.add_section('wupeiqi')
    31 #config.write(open('i.cfg', "w"))
    32   
    33   
    34 #config.set('group2','k1',11111)
    35 #config.write(open('i.cfg', "w"))
    36   
    37 #config.remove_option('group2','age')
    38 #config.write(open('i.cfg', "w"))

    十一、hashlib

    用于加密相关的操作,代替了md5模块的sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法

     1 import hashlib
     2 #---------md5----------
     3 hash = hashlib.md5()
     4 hash.update('admin')
     5 print(hash.hexdigest())
     6 #---------sha1----------
     7 hash = hashlib.sha1()
     8 hash.update('admin')
     9 print(hash.hexdigest())
    10 #---------sha256----------
    11 hash = hashlib.sha256()
    12 hash.update('admin')
    13 print(hash.hexdigest())
    14 #---------sha384----------
    15 hash = hashlib.sha384()
    16 hash.update('admin')
    17 print(hash.hexdigest())
    18 #---------sha512----------
    19 hash = hashlib.sha512()
    20 hash.update('admin')
    21 print(hash.hexdigest())

     

    以上加密算法虽然依然非常厉害,但有时候存在缺陷,即:通过撞库可以反解。所以,有必要加密算法中添加自定义key再来做加密。

    1 import hashlib
    2 #----------md5----------
    3 hash = hashlib.md5('898oaFs09f|')
    4 hash.update('admin')
    5 print(hash.hexdigest())

     

    最后,python还有一个hmac模块,它内部对我们创建key和内容再进行处理然后再加密

    1 import hmac
    2 h = hmac.new('wupeiqi')
    3 h.update('hello wo')
    4 print(h.hexdigest())

     

    这已经是最牛逼的了。

    十二、subprocess

    运行python的时候,我们都是在创建并运行一个进程。像Linux进程那样,一个进程可以fork一个子进程,并让这个子进程exec另外一个程序。在Python中,我们通过标准库中的subprocess包来fork一个子进程,并运行一个外部的程序。
    subprocess包中定义有数个创建子进程的函数,这些函数分别以不同的方式创建子进程,所以我们可以根据需要来从中选取一个使用。另外subprocess还提供了一些管理标准流(standard stream)和管道(pipe)的工具,从而在进程间使用文本通信。

    常用subprocess方法示例

    #执行命令,返回命令执行状态 , 0 or 非0
    >>> retcode = subprocess.call(["ls", "-l"])

    #执行命令,如果命令结果为0,就正常返回,否则抛异常
    >>> subprocess.check_call(["ls", "-l"])
    0

    #接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果 
    >>> subprocess.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls')

    #接收字符串格式命令,并返回结果
    >>> subprocess.getoutput('ls /bin/ls')
    '/bin/ls'

    #执行命令,并返回结果,注意是返回结果,不是打印,下例结果返回给res
    >>> res=subprocess.check_output(['ls','-l'])
    >>> res
    b'total 0 drwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM '

    #上面那些方法,底层都是封装的subprocess.Popen
    poll()
    Check if child process has terminated. Returns returncode

    wait()
    Wait for child process to terminate. Returns returncode attribute.


    terminate() 杀掉所启动进程
    communicate() 等待任务结束

    stdin 标准输入

    stdout 标准输出

    stderr 标准错误

    pid
    The process ID of the child process.

    #例子
    >>> p = subprocess.Popen("df -h|grep disk",stdin=subprocess.PIPE,stdout=subprocess.PIPE,shell=True)
    >>> p.stdout.read()
    b'/dev/disk1 465Gi 64Gi 400Gi 14% 16901472 104938142 14% / '

    调用subprocess.run(...)是推荐的常用方法,在大多数情况下能满足需求,但如果你可能需要进行一些复杂的与系统的交互的话,你还可以用subprocess.Popen(),语法如下:

    1 p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} ;",shell=True,stdout=subprocess.PIPE)
    2 print(p.stdout.read())

     

    可用参数:

    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用
    • startupinfo与createionflags只在windows下有效将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

    终端输入的命令分为两种:

    • 输入即可得到输出,如:ifconfig
    • 输入进行某环境,依赖再输入,如:python

    需要交互的命令示例

     1 import subprocess
     2  
     3 obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
     4 obj.stdin.write('print 1 
     ')
     5 obj.stdin.write('print 2 
     ')
     6 obj.stdin.write('print 3 
     ')
     7 obj.stdin.write('print 4 
     ')
     8  
     9 out_error_list = obj.communicate(timeout=10)
    10 print out_error_list

    subprocess实现sudo自动输入密码

     1 import subprocess
     2  
     3 def mypass():
     4     mypass = '123' #or get the password from anywhere
     5     return mypass
     6  
     7 echo = subprocess.Popen(['echo',mypass()],
     8                         stdout=subprocess.PIPE,
     9                         )
    10  
    11 sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
    12                         stdin=echo.stdout,
    13                         stdout=subprocess.PIPE,
    14                         )
    15  
    16 end_of_pipe = sudo.stdout
    17  
    18 print "Password ok 
     Iptables Chains %s" % end_of_pipe.read()

    十三、logging

    很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告到呢个信息输出,python中的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为debug(),info(),warning(),error()和critical()5个级别。

    最简单的用法

    1 import logging
    2 logging.warning('user [alex] attempted wrong password more than 3 times')
    3 logging.critical('server is down')
    4 
    5 #输出:WARNING:root:user [alex] attempted wrong password more than 3 times
    6 #      CRITICAL:root:server is down

     

    把日志写到文件里

    1 import logging
    2  
    3 logging.basicConfig(filename='example.log',level=logging.INFO)
    4 logging.debug('This message should go to the log file')
    5 logging.info('So should this')
    6 logging.warning('And this, too')

     

    下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

    logging.basicConfig(filename='example.log',level=logging.INFO)

    上面的日志格式没有加时间,现在来加时间

    1 import logging
    2 logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    3 logging.warning('is when this event was logged.')
    4 #输出:03/16/2017 04:50:00 PM is when this event was logged.

     

    日志格式

    %(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

    用户输出的消息

    如果想同时把log打印在屏幕和文件日志里,就需要了解一点复杂的知识 了


    Python 使用logging模块记录日志涉及四个主要类,使用官方文档中的概括最为合适:

    logger提供了应用程序可以直接使用的接口;

    handler将(logger创建的)日志记录发送到合适的目的输出;

    filter提供了细度设备来决定输出哪条日志记录;

    formatter决定日志记录的最终输出格式。

    logger
    每个程序在输出信息之前都要获得一个Logger。Logger通常对应了程序的模块名,比如聊天工具的图形界面模块可以这样获得它的Logger:
    LOG=logging.getLogger(”chat.gui”)
    而核心模块可以这样:
    LOG=logging.getLogger(”chat.kernel”)

    Logger.setLevel(lel):指定最低的日志级别,低于lel的级别将被忽略。debug是最低的内置级别,critical为最高
    Logger.addFilter(filt)、Logger.removeFilter(filt):添加或删除指定的filter
    Logger.addHandler(hdlr)、Logger.removeHandler(hdlr):增加或删除指定的handler
    Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical():可以设置的日志级别

     

    handler

    handler对象负责发送相关的信息到指定目的地。Python的日志系统有多种Handler可以使用。有些Handler可以把信息输出到控制台,有些Logger可以把信息输出到文件,还有些 Handler可以把信息发送到网络上。如果觉得不够用,还可以编写自己的Handler。可以通过addHandler()方法添加多个多handler
    Handler.setLevel(lel):指定被处理的信息级别,低于lel级别的信息将被忽略
    Handler.setFormatter():给这个handler选择一个格式
    Handler.addFilter(filt)、Handler.removeFilter(filt):新增或删除一个filter对象


    每个Logger可以附加多个Handler。接下来我们就来介绍一些常用的Handler:
    1) logging.StreamHandler
    使用这个Handler可以向类似与sys.stdout或者sys.stderr的任何文件对象(file object)输出信息。它的构造函数是:
    StreamHandler([strm])
    其中strm参数是一个文件对象。默认是sys.stderr


    2) logging.FileHandler
    和StreamHandler类似,用于向一个文件输出日志信息。不过FileHandler会帮你打开这个文件。它的构造函数是:
    FileHandler(filename[,mode])
    filename是文件名,必须指定一个文件名。
    mode是文件的打开方式。参见Python内置函数open()的用法。默认是’a',即添加到文件末尾。

    3) logging.handlers.RotatingFileHandler
    这个Handler类似于上面的FileHandler,但是它可以管理文件大小。当文件达到一定大小之后,它会自动将当前日志文件改名,然后创建 一个新的同名日志文件继续输出。比如日志文件是chat.log。当chat.log达到指定的大小之后,RotatingFileHandler自动把 文件改名为chat.log.1。不过,如果chat.log.1已经存在,会先把chat.log.1重命名为chat.log.2。。。最后重新创建 chat.log,继续输出日志信息。它的构造函数是:
    RotatingFileHandler( filename[, mode[, maxBytes[, backupCount]]])
    其中filename和mode两个参数和FileHandler一样。
    maxBytes用于指定日志文件的最大文件大小。如果maxBytes为0,意味着日志文件可以无限大,这时上面描述的重命名过程就不会发生。
    backupCount用于指定保留的备份文件的个数。比如,如果指定为2,当上面描述的重命名过程发生时,原有的chat.log.2并不会被更名,而是被删除。


    4) logging.handlers.TimedRotatingFileHandler
    这个Handler和RotatingFileHandler类似,不过,它没有通过判断文件大小来决定何时重新创建日志文件,而是间隔一定时间就 自动创建新的日志文件。重命名的过程与RotatingFileHandler类似,不过新的文件不是附加数字,而是当前时间。它的构造函数是:
    TimedRotatingFileHandler( filename [,when [,interval [,backupCount]]])
    其中filename参数和backupCount参数和RotatingFileHandler具有相同的意义。
    interval是时间间隔。
    when参数是一个字符串。表示时间间隔的单位,不区分大小写。它有以下取值:
    S 秒
    M 分
    H 小时
    D 天
    W 每星期(interval==0时代表星期一)
    midnight 每天凌晨

     1 import logging
     2  
     3 #create logger
     4 logger = logging.getLogger('TEST-LOG')
     5 logger.setLevel(logging.DEBUG)
     6  
     7  
     8 # create console handler and set level to debug
     9 ch = logging.StreamHandler()
    10 ch.setLevel(logging.DEBUG)
    11  
    12 # create file handler and set level to warning
    13 fh = logging.FileHandler("access.log")
    14 fh.setLevel(logging.WARNING)
    15 # create formatter
    16 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    17  
    18 # add formatter to ch and fh
    19 ch.setFormatter(formatter)
    20 fh.setFormatter(formatter)
    21  
    22 # add ch and fh to logger
    23 logger.addHandler(ch)
    24 logger.addHandler(fh)
    25  
    26 # 'application' code
    27 logger.debug('debug message')
    28 logger.info('info message')
    29 logger.warn('warn message')
    30 logger.error('error message')
    31 logger.critical('critical message')

    注:本文仅为学习笔记、摘要。

    详细来源:http://www.cnblogs.com/alex3714/articles/5161349.html

         http://www.cnblogs.com/wupeiqi/articles/4963027.html 

     

  • 相关阅读:
    Python-炫酷二维码
    Dictionary 序列化与反序列化
    获取数据库所有表名与字段名
    LinQ To Object 基本用法
    使用jq操作脚本生成元素的事件
    表单验证如何让select设置为必选
    js实现复制功能兼容ios
    微信小程序使用函数防抖解决重复点击消耗性能问题
    electronr进行签名与公证
    使用electron在mac升级签名后进行升级出现“QRLUpdaterErrorDomain”的错误
  • 原文地址:https://www.cnblogs.com/lyonyang/p/6539085.html
Copyright © 2011-2022 走看看