Python(六)-常用模块

目录:
    1、模块介绍
    2、time & datetime模块
    3、rendom
    4、os
    5、sys
    6、shutil
    7、json & picle
    8、shelve
    9、xml处理
    10、yaml处理
    11、chonfigparser
    12、hashlib
    13、subprocess
    14、logging模块
    15、re正则表达式
第一章:模块介绍
    模块,用一坨代码实现了某个功能的代码集合。
    类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合,而对于一个复杂的功能来,可能需要多个函数才能完成(函数又可以在不同的.py文件中),n个.py文件组成的代码集合就成为模块。
    如:os是系统相关的模块;open是文件操作相关的模块
    模块分为三种:
        1、自定义模块
        2、内置标准模块(又称标准库)
        3、开源模块

1.1 time模块
返回处理时间
            print(time.clock()) #返回处理时间,3.3开始已经废弃,改成了time.provese_time(),测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来。
        
                结果:0.053643
        
        返回与utc时间的时间差
            print(time.altzone)#返回与utc时间的时间差,以秒计算
        
                结果:-28800
        
        返回时间格式
            print(time.asctime())#返回时间格式"Thu Nov 17 21:22:58 2016"
        
                结果:Thu Nov 17 21:41:59 2016
        返回本地时间的时间对象
            print(time.localtime())#返回本地时间的struct time对象格式(时间对象)
                
                结果:time.struct_time(tm_year=2016, tm_mon=11, tm_mday=17, tm_hour=21, tm_min=41, tm_sec=59, tm_wday=3, tm_yday=322, tm_isdst=0)
                
        返回utc时间的时间对象
            print(time.gmtime(time.time()-800000))#返回utc时间的struc时间对象格式
            
                结果:time.struct_time(tm_year=2016, tm_mon=11, tm_mday=8, tm_hour=7, tm_min=28, tm_sec=39, tm_wday=1, tm_yday=313, tm_isdst=0)
                
        返回时间格式
            print(time.asctime(time.localtime())) #返回时间格式"Thu Nov 17 21:26:24 2016"
                
                结果:Thu Nov 17 21:41:59 2016
                
        返回时间格式
            print(time.ctime())#返回同上"Thu Nov 17 21:27:44 2016"
            
                结果:Thu Nov 17 21:41:59 2016
            
        日期字符串--->时间戳
            string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将日期字符串转换成struct时间对象格式
            print(string_2_struct)
            
                结果:time.struct_time(tm_year=2016, tm_mon=5, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=143, tm_isdst=-1)
            
            string_2_stamp = time.mktime(string_2_struct)#将struct时间对象转成时间戳
            print(string_2_stamp)
                
                结果:1463846400.0
        将时间戳转换为字符串格式
            print(time.gmtime(time.time() -86640)) #将utc时间转换为struct_time格式
            
                结果:time.struct_time(tm_year=2016, tm_mon=11, tm_mday=16, tm_hour=13, tm_min=37, tm_sec=59, tm_wday=2, tm_yday=321, tm_isdst=0)

 

1.2datetime模块
import datetime,time

#打印当前时间
    print(datetime.datetime.now())
        结果:
            2016-11-18 10:53:18.956577
#打印当前日期
    print(datetime.date.fromtimestamp(time.time()))#时间戳直接转成日期格式
        结果:2016-11-18
        
#时间的日期加减,小时的加减,分钟的加减
    print(datetime.datetime.now()+datetime.timedelta(3)) #当前时间+3天,-3天,都一样,小时使用hours=3,分钟加减为minutes=30
        结果:2016-11-21 10:53:18.956676

#时间替换
    c_time=datetime.datetime.now()
    print(c_time.replace(minute=3,hour=2))
        结果:2016-11-18 02:03:18.956695

1.2.1时间格式

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

1.3 random 模块

import random
#
print(random.random())#用来生成一个0-1的浮点数
print(random.randint(1,10)) #生成一个1-10的随机数
print(random.randrange(1,10,3)) #指定间隔取随机数




#生成随机验证码
    import random
    
    chenckcode=''   #首先定义一个空字符串
    for i in range(4):  #循环4次,即想要几个字符串就循环几次
        current = random.randrange(0,4)
        if current !=i:
            temp = chr(random.randint(65,90))
            # print(temp)
        else:
            temp = random.randint(0,9)
            # print(temp)
        chenckcode +=str(temp)
    print(chenckcode)

1.4 os 模块

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

1.5 sys模块

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

1.6 json& pickle 模块

json,#用于字符串和python数据类型间进行转换
pickle,#用于python特有的类型和python的数据类型间进行转换

Json模块提供了四个功能:dumps,dump,loads,load
pickle模块提供四个功能:dumps,dump,loads,load

import pickle

data = {
    'r1':123,
    'r2':'hello'
}

#pickle.dumps,将数据通过特殊的形式转换为只有python语言认识的字符串
p_str = pickle.dumps(data)
print(p_str)

#pickle.dump 将数据通过特殊的形式转换为只有python语言认识的字符串,并写入文件
with open('cc.txt','w') as f:
    pickle.dump(data,f)

import json

#json.dumps将数据通过特殊的形式转换为所有程序语言都认识的字符串
j_str = json.dumps(data)
print(j_str)

#json.dump将数据通过特殊的形式转换为所有程序语言都认识的字符串,并写入文件
with open('jj.txt','w') as f:
    json.dump(data,f)

1.7 Subprocess模块

常用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\ndrwxr-xr-x 12 alex staff 408 Nov 2 11:05 OldBoyCRM\n'

    #上面那些方法,底层都是封装的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% /\n'
     


    
    >>> subprocess.run(["ls", "-l"])  # doesn't capture output
    CompletedProcess(args=['ls', '-l'], returncode=0)
     
    >>> subprocess.run("exit 1", shell=True, check=True)
    Traceback (most recent call last):
      ...
    subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1
     
    >>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
    CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
    stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

 

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

    p = subprocess.Popen("find / -size +1000000 -exec ls -shl {} \;",shell=True,stdout=subprocess.PIPE)
    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 -> 同意使用 \n
        startupinfo与createionflags只在windows下有效
        将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

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

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

需要交互的命令示例
        
    import subprocess
     
    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    obj.stdin.write('print 1 \n ')
    obj.stdin.write('print 2 \n ')
    obj.stdin.write('print 3 \n ')
    obj.stdin.write('print 4 \n ')
     
    out_error_list = obj.communicate(timeout=10)
    print out_error_list
    
    
subprocess实现sudo 自动输入密码
    
    import subprocess
     
    def mypass():
        mypass = '123' #or get the password from anywhere
        return mypass
     
    echo = subprocess.Popen(['echo',mypass()],
                            stdout=subprocess.PIPE,
                            )
     
    sudo = subprocess.Popen(['sudo','-S','iptables','-L'],
                            stdin=echo.stdout,
                            stdout=subprocess.PIPE,
                            )
     
    end_of_pipe = sudo.stdout
     
    print "Password ok \n Iptables Chains %s" % end_of_pipe.read()

1.8 logging 模块

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

简单用法
    import logging

    logging.warning("user [chenxin] attempted wrong password more than 3 times")
    logging.critical("server is down")
        输出:
            WARNING:root:user [chenxin] attempted wrong password more than 3 times
            CRITICAL:root:server is down
            
这几个日志级别分别代表什么意思?
    level               意思
    DEBUG               详细信息,通常仅在诊断问题时打印,(调试日志)
    INFO                正常访问日志
    WARNING             警告日志
    ERROR               错误日志
    CRITICAL            程序宕机日志

把日志写到文件里
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    logging.warning('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.9 hashlib 模块

用于加密相关的操作,3.x里替代了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法。
    
        import hashlib
        
        # m = hashlib.md5()
        # m.update(b'Hello')
        # m.update(b"It's me")
        # print(m.digest())
        # m.update(b"It's been a long time since last time we ...")
        # print(m.digest()) #2进制格式hash
        # print(len(m.hexdigest())) #16进制格式hash
        
        '''
        def digest(self, *args, **kwargs): # real signature unknown
            """ Return the digest value as a string of binary data. """
            pass
        
        def hexdigest(self, *args, **kwargs): # real signature unknown
            """ Return the digest value as a string of hexadecimal digits. """
            pass
        
        '''
        
        ########md5########
        hash = hashlib.md5()
        hash.update(b'admin')
        print(hash.hexdigest())
        
        #######sha1#######
        
        hash = hashlib.sha1()
        hash.update(b'admin')
        print(hash.hexdigest())
        
        ######sha256#####
        
        hash = hashlib.sha256()
        hash.update(b'admin')
        print(hash.hexdigest())
        
        # ######## sha384 ########
        
        hash = hashlib.sha384()
        hash.update(b'admin')
        print(hash.hexdigest())
        
        # ######## sha512 ########
        
        hash = hashlib.sha512()
        hash.update(b'admin')
        print(hash.hexdigest())

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

        import hmac
        h = hmac.new('wueiqi')
        h.update('hellowo')
        print h.hexdigest()

2.0 ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在python3.x版本变更为configparser
    
    
#写入一个配置文件
    # 写入配置文件
    config = configparser.ConfigParser()  #将一个配置文件的的语法赋予简单变量使用
    config['DEFAULT'] = {                   #将配置一个默认的模块,即全局配置,DEFAULT必须大写
        'ServerAliveInterval':'45',
        'Compression':'yes',
        'CompressionLevel':'9'
    }
    
    config['bitbucket.org']= {}         #定义一个空的配置bitbucket.org
    config['bitbucket.org']['User']='hg'    #单个往空配置中添加一个user配置
    config['topsecret.server.com'] = {}     #在定义一个空配置名字为topsecret.server.com
    topsevret = config['topsecret.server.com']  #将topsecret.server.com模块赋予一个简单的变量
    topsevret['Host Port'] = '50022'            #添加一个配置
    topsevret['ForwardX11'] = 'on'              #添加配置
    config['DEFAULT']['ForwardX11']='yes'          #给DEFAULT配置添加一个配置
    with open('config.ini','w') as configfile:      #打开文件
        config.write(configfile)                    #将配置写入文件中
#写入后的文件内容
    [DEFAULT]
    compression = yes
    compressionlevel = 9
    serveraliveinterval = 45
    forwardx11 = yes
    
    [bitbucket.org]
    user = hg
    
    [topsecret.server.com]
    host port = 50022
    forwardx11 = on

   
#查看配置文件与取值
    
    # >>> import configparser           #导入模块
    # >>> config = configparser.ConfigParser()   #将读取的语法赋予变量
    # >>> config.sections()                       #将所有的option以列表的形式打印出来
    # []
    # >>> config.read('example.ini')                #读取一个配置文件
    # ['example.ini']   
    # >>> config.sections()                         #读取配置文件中的所有标签字段
    # ['bitbucket.org', 'topsecret.server.com']
    # >>> 'bitbucket.org' in config                 #判断一个标签是否在读取的这个文件中
    # True
    # >>> 'bytebong.com' in config                  #判断
    # False
    # >>> config['bitbucket.org']['User']           #读取bitbucket.org中的user的值
    # 'hg'
    # >>> config['DEFAULT']['Compression']           #读取默认全局配置中Compression的值
    # 'yes'
    # >>> topsecret = config['topsecret.server.com']   #将读取配置文件中的topsecret.server.com标签赋予一个变量
    # >>> topsecret['ForwardX11']                       #读取topsecret.server.com标签下ForwardX11的值,注意,正常文件中的标签没有这个配置,因为在全局中有
    # 'no'
    # >>> topsecret['Port']             #读取topsecret.server.com的port的值
    # '50022'
    # >>> for key in config['bitbucket.org']: print(key)    #循环遍历读取配置文件这个标签下的所有key值
    # ...
    # user
    # compressionlevel
    # serveraliveinterval
    # compression
    # forwardx11
    # >>> config['bitbucket.org']['ForwardX11'] #读取配置
    # 'yes'
    
#configparser增删改查语法
# 
    # [section1]
    # k1 = v1
    # k2:v2
    # 
    # [section2]
    # k1 = v1
    # 
    # import ConfigParser
    # 
    # config = ConfigParser.ConfigParser()
    # config.read('i.cfg')
    
    # ########## 读 ##########
    # secs = config.sections()
    # print secs
    # options = config.options('group2')
    # print options
    
    # item_list = config.items('group2')
    # print item_list
    
    # val = config.get('group1','key')
    # val = config.getint('group1','key')
    
    # ########## 改写 ##########
    # sec = config.remove_section('group1')
    # config.write(open('i.cfg', "w"))
    
    # sec = config.has_section('wupeiqi')
    # sec = config.add_section('wupeiqi')
    # config.write(open('i.cfg', "w"))
    
    
    # config.set('group2','k1',11111)
    # config.write(open('i.cfg', "w"))
    
    # config.remove_option('group2','age')
    # config.write(open('i.cfg', "w"))

2.1 shelve模块

shelve模块是一个简单的k,v将内存数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据格式。
import shelve
d = shelve.open('shelve_test') #打开一个文件
class Test(object):
    def __init__(self,n):
        self.n = n

t = Test(123)
t2 = Test(123334)

name = ['chenxin','test','pascc']
d['test'] =name  #持久化列表

d['t1'] =t #持久化类
d['t2']=t2

d.close()

1.3 re模块

常用正则表达式符号
    
    '.'     默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
    '^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
    '$'     匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
    '*'     匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac")  结果为['abb', 'ab', 'a']
    '+'     匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
    '?'     匹配前一个字符1次或0次
    '{m}'   匹配前一个字符m次
    '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
    '|'     匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
    '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
    '\A'    只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
    '\Z'    匹配字符结尾,同$
    '\d'    匹配数字0-9
    '\D'    匹配非数字
    '\w'    匹配[A-Za-z0-9]
    '\W'    匹配非[A-Za-z0-9]
    's'     匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
 
    '(?P<name>...)' 分组匹配 re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 结果{'province': '3714', 'city': '81', 'birthday': '1993'}

最常用的匹配语法
    re.match 从头开始匹配
    re.search 匹配包含
    re.findall 把所有匹配到的字符放到以列表中的元素返回
    re.splitall 以匹配到的字符当做列表分隔符
    re.sub      匹配字符并替换

反斜杠的困扰
    与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。同样,匹配一个数字的"\\d"可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

 

仅需轻轻知道的几个匹配模式
    
    re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
    M(MULTILINE): 多行模式,改变'^''$'的行为(参见上图)
    S(DOTALL): 点任意匹配模式,改变'.'的行为

 


posted @ 2016-11-18 20:25  技术处理你  阅读(311)  评论(0编辑  收藏  举报