• 五、常用模块


    1. 模块介绍
    2. time &datetime模块
    3. random
    4. os
    5. sys
    6. shutil
    7. json & picle
    8. shelve
    9. xml处理
    10. yaml处理
    11. configparser
    12. hashlib
    13. subprocess
    14. logging模块
    15. re正则表达式

    原 文:http://www.cnblogs.com/alex3714/articles/5161349.html

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

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

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

    模块分为三种:

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

    time & datetime模块

     1 #_*_coding:utf-8_*_
     2 __author__ = 'Alex Li'
     3 
     4 import time
     5 
     6 
     7 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
     8 # print(time.altzone)  #返回与utc时间的时间差,以秒计算
     9 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
    10 # print(time.localtime()) #返回本地时间 的struct time对象格式
    11 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
    12 
    13 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
    14 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
    15 
    16 
    17 
    18 # 日期字符串 转成  时间戳
    19 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
    20 # print(string_2_struct)
    21 # #
    22 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
    23 # print(struct_2_stamp)
    24 
    25 
    26 
    27 #将时间戳转为字符串格式
    28 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
    29 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
    30 
    31 
    32 
    33 
    34 
    35 #时间加减
    36 import datetime
    37 
    38 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
    39 #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
    40 # print(datetime.datetime.now() )
    41 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
    42 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
    43 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
    44 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
    45 
    46 
    47 #
    48 # c_time  = datetime.datetime.now()
    49 # print(c_time.replace(minute=3,hour=2)) #时间替换
    View Code
    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模块

    随机数

    mport random
    print random.random()
    print random.randint(1,2)
    print random.randrange(1,10)

    生成随机验证码

     1 import random
     2 checkcode = ''
     3 for i in range(4):
     4     current = random.randrange(0,4)
     5     if current != i:
     6         temp = chr(random.randint(65,90))
     7     else:
     8         temp = random.randint(0,9)
     9     checkcode += str(temp)
    10 print checkcode

    OS模块  

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

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

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

    shutil.copyfileobj(fsrc, fdst[, length])
    将文件内容拷贝到另一个文件中,可以部分内容
    
    shutil.copyfile(src, dst)
    拷贝文件
    
    shutil.copymode(src, dst)
    仅拷贝权限。内容、组、用户均不变
    
    shutil.copystat(src, dst)
    拷贝状态的信息,包括:mode bits, atime, mtime, flags
    
    shutil.copy(src, dst)
    拷贝文件和权限
    
    shutil.copy2(src, dst)
    拷贝文件和状态信息
    
    shutil.ignore_patterns(*patterns)
    shutil.copytree(src, dst, symlinks=False, ignore=None)
    递归的去拷贝文件
    例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))
    
    shutil.rmtree(path[, ignore_errors[, onerror]])
    递归的去删除文件
    
    shutil.move(src, dst)
    递归的去移动文件
    
    shutil.make_archive(base_name, format,...)
    
    创建压缩包并返回文件路径,例如:zip、tar
    
    base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
    如:www                        =>保存至当前路径
    如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    format:    压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    root_dir:    要压缩的文件夹路径(默认当前目录)
    owner:    用户,默认当前用户
    group:    组,默认当前组
    logger:    用于记录日志,通常是logging.Logger对象
    
    shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的

    import zipfile
    
    # 压缩
    z = zipfile.ZipFile('laxi.zip', 'w')
    z.write('a.log')
    z.write('data.data')
    z.close()
    
    # 解压
    z = zipfile.ZipFile('laxi.zip', 'r')
    z.extractall()
    z.close()


    import tarfile
    
    # 压缩
    tar = tarfile.open('your.tar','w')
    tar.add('/Users/wupeiqi/PycharmProjects/bbs2.zip', arcname='bbs2.zip')
    tar.add('/Users/wupeiqi/PycharmProjects/cmdb.zip', arcname='cmdb.zip')
    tar.close()
    
    # 解压
    tar = tarfile.open('your.tar','r')
    tar.extractall()  # 可设置解压地址
    tar.close()
     

    json & pickle 模块

    用于序列化的两个模块

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

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

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

    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 = ["alex","rain","test"]
    d["test"] = name #持久化列表
    d["t1"] = t      #持久化类
    d["t2"] = t2
     
    d.close()

    xml处理模块

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

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

    import xml.etree.ElementTree as ET
     
    tree = ET.parse("xmltest.xml")
    root = tree.getroot()
    print(root.tag)
     
    #遍历xml文档
    for child in root:
        print(child.tag, child.attrib)
        for i in child:
            print(i.tag,i.text)
     
    #只遍历year 节点
    for node in root.iter('year'):
        print(node.tag,node.text)

    PyYAML模块

    Python也可以很容易的处理ymal文档格式,只不过需要安装一个模块,参考文档:http://pyyaml.org/wiki/PyYAMLDocumentation 

    ConfigParser模块

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

    来看一个好多软件的常见文档格式如下

    [DEFAULT]
    ServerAliveInterval = 45
    Compression = yes
    CompressionLevel = 9
    ForwardX11 = yes
     
    [bitbucket.org]
    User = hg
     
    [topsecret.server.com]
    Port = 50022
    ForwardX11 = no

    用python:

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

    hashlib模块  

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

    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% / '

    logging模块  

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

    LevelWhen it’s used
    DEBUG Detailed information, typically of interest only when diagnosing problems.
    INFO Confirmation that things are working as expected.
    WARNING An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
    ERROR Due to a more serious problem, the software has not been able to perform some function.
    CRITICAL A serious error, indicating that the program itself may be unable to continue running.

    re模块

    常用正则表达式符号

    '.'     默认匹配除
    之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
    '^'     匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","
    abc
    eee",flags=re.MULTILINE)
    '$'     匹配字符结尾,或e.search("foo$","bfoo
    sdfsf",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") 是匹配不到的
    ''    匹配字符结尾,同$
    'd'    匹配数字0-9
    'D'    匹配非数字
    'w'    匹配[A-Za-z0-9]
    'W'    匹配非[A-Za-z0-9]
    's'     匹配空白字符、	、
    、
     , re.search("s+","ab	c1
    3").group() 结果 '	'
     
    '(?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'}
  • 相关阅读:
    mysql 存在该记录则更新,不存在则插入的sql
    php计划任务的实现
    Dictionary<TKey,TValue>泛型封装
    win10家庭版 获取 syswow64权限
    发送带参数post请求
    visual studio自动向量化
    交叉编译
    opencv笔记meanshift&camshift
    [源码学习]调试Razor从哪里开始
    [转]官网下载Google Chrome离线安装包
  • 原文地址:https://www.cnblogs.com/jiangzijiang/p/8513291.html
Copyright © 2020-2023  润新知