zoukankan      html  css  js  c++  java
  • 循序渐进Python3(五) -- 初识模块

    什么是模块?

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

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

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

    import module  #导入模块下的全部模块
    from module.xx.xx import *  #导入模块下的全部模块
    from module.xx.xx import xx  #导入某块下的指定模块
    from module.xx.xx import xx as rename   #导入指定模块并给他设置别名 
    

    1、os用于提供系统级别的操作

    import 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下为"	
    ",Linux下为"
    "
    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所指向的文件或者目录的最后修改时间
    

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

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

    3、json 和 pickle

    用于序列化的两个模块

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

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

    json dumps把数据类型转换成字符串 dump把数据类型转换成字符串并存储在文件中  loads把字符串转换成数据类型  load把文件打开从字符串转换成数据类型

    pickle同理

    现在有个场景在不同设备之间进行数据交换很low的方式就是传文件,dumps可以直接把服务器A中内存的东西发给其他服务器,比如B服务器、
    在很多场景下如果用pickle的话那A的和B的程序都的是python程序这个是不现实的,很多时候都是不同的程序之间的内存交换怎么办?就用到了json(和html类似的语言)
    并且josn能dump的结果更可读,那么有人就问了,那还用pickle做什么不直接用josn,是这样的josn只能把常用的数据类型序列化(列表、字典、列表、字符串、数字、),比如日期格式、类对象!josn就不行了。
    为什么他不能序列化上面的东西呢?因为josn是跨语言的!

    例子如下:

    复制代码
    #!/usr/bin/env python
    #-*- coding:utf-8 -*-
    __author__ = 'luotianshuai'
    
    
    import json
    
    test_dic = {'name':'luotianshuai','age':18}
    print '未dumps前类型为:',type(test_dic)
    #dumps 将数据通过特殊的形式转换为所有程序语言都识别的字符串
    json_str = json.dumps(test_dic)
    print 'dumps后的类型为:',type(json_str)
    
    #loads 将字符串通过特殊的形式转为python是数据类型
    
    new_dic = json.loads(json_str)
    print '重新loads加载为数据类型:',type(new_dic)
    
    print '*' * 50
    
    #dump 将数据通过特殊的形式转换为所有语言都识别的字符串并写入文件
    with open('test.txt','w') as openfile:
        json.dump(new_dic,openfile)
        print 'dump为文件完成!!!!!'
    #load 从文件读取字符串并转换为python的数据类型
    
    with open('test.txt','rb') as loadfile:
        load_dic = json.load(loadfile)
        print 'load 并赋值给load_dic后的数据类型:',type(load_dic)

    4、time & datetime

    import time
    import datetime
    
    print(time.clock()) #返回处理器时间,3.3开始已废弃
    print(time.process_time()) #返回处理器时间,3.3开始已废弃
    print(time.time()) #返回当前系统时间戳
    print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间
    print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式
    print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式
    print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间
    print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式
    #time.sleep(4) #sleep
    print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式
    print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式
    
    #datetime module
    
    print(datetime.date.today()) #输出格式 2016-01-26
    print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式
    current_time = datetime.datetime.now() #
    print(current_time) #输出2016-01-26 19:04:30.335935
    print(current_time.timetuple()) #返回struct_time格式
    
    #datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
    print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换
    
    str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式
    new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天
    new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天
    new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时
    new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120s
    print(new_date)
    

    5、logging模块  


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

    最简单用法
    import logging

    logging.warning("user [alex] attempted wrong password more than 3 times")
    logging.critical("server is down")

    #输出
    WARNING:root:user [alex] attempted wrong password more than 3 times
    CRITICAL:root:server is down
    看一下这几个日志级别分别代表什么意思

    Level When 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.

    如果想把日志写到文件里,也很简单

    import logging

    logging.basicConfig(filename='example.log',level=logging.INFO)
    logging.debug('This message should go to the log file')
    logging.info('So should this')
    logging.warning('And this, too')
    其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。

    logging.basicConfig(filename='example.log',level=logging.INFO)
    感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!

    import logging
    logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    logging.warning('is when this event was logged.')

    #输出
    12/12/2010 11:46:36 AM is when this event was logged.
      

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

    The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.

    Loggers expose the interface that application code directly uses.
    Handlers send the log records (created by loggers) to the appropriate destination.
    Filters provide a finer grained facility for determining which log records to output.
    Formatters specify the layout of log records in the final output.

    import logging

    #create logger
    logger = logging.getLogger('TEST-LOG')
    logger.setLevel(logging.DEBUG)


    # create console handler and set level to debug
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    # create file handler and set level to warning
    fh = logging.FileHandler("access.log")
    fh.setLevel(logging.WARNING)
    # create formatter
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    # add formatter to ch and fh
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)

    # add ch and fh to logger
    logger.addHandler(ch)
    logger.addHandler(fh)

    # 'application' code
    logger.debug('debug message')
    logger.info('info message')
    logger.warn('warn message')
    logger.error('error message')
    logger.critical('critical message')

    6、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()
    

    7、subprocess

    subprocess.Popen(...) :用于执行复杂的系统命令

    复制代码
    '''
    参数:
    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()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
    '''

    import subprocess
    ret1 = subprocess.Popen(["mkdir","t1"])
    ret2 = subprocess.Popen("mkdir t2", shell=True)
    复制代码


    复制代码
    import subprocess

    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) #启动一个交互的的程序,但是你的有标准的输入和输出、错误,类似一个管道
    #stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE 类似管道
    #这个的作用是,你可以用python把外部的程序长期启动了!
    obj.stdin.write('print 1 ')
    obj.stdin.write('print 2 ')
    obj.stdin.write('print 3 ')
    obj.stdin.write('print 4 ')
    obj.stdin.close() #关闭标准输入

    #这里输入完成了是不是的把他的输出读出来?
    cmd_out = obj.stdout.read() #获取启动的进程的标准输出
    obj.stdout.close() #关闭标准输出
    cmd_error = obj.stderr.read() #获取启动的进程的标准错误
    obj.stderr.close() #关闭启动程序的标准错误

    print cmd_out #打印标准输出 (空的?)
    print cmd_error #打印标准错误

    '''
    #>>> obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    #>>> obj.stdin.write('print 1 ')
    #>>> obj.stdin.write('print 2 ')
    #>>> obj.stdin.write('print 3 ')
    #>>> obj.stdin.write('print 4 ')
    #Traceback (most recent call last):
    # File "<stdin>", line 1, in <module>
    #IOError: [Errno 32] Broken pipe #这里是因为,pipe管道最大的能允许保存的内容为64k如果大于64k就会出现问题,线面的communicate()方法就会把输出放到内存
    '''



    可参考http://www.cnblogs.com/wupeiqi/articles/5501365.html


    #tim@tim:~$ ps -ef |grep -i python
    #root 2290 2280 0 21:38 pts/0 00:00:00 python
    #root 2313 2290 0 21:47 pts/0 00:00:00 [python] <defunct> #这里会产生一个僵尸进程,直接使用obj.wait() 原因请看下面的
    #tim 2317 2292 0 21:48 pts/3 00:00:00 grep --color=auto -i python
    #tim@tim:~$



    import subprocess
    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    obj.stdin.write('print 1 ')
    obj.stdin.write('print 2 ')
    obj.stdin.write('print 3 ')
    obj.stdin.write('print 4 ')

    out_error_list = obj.communicate()
    print out_error_list



    import subprocess
    obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out_error_list = obj.communicate('print "hello"')
    print out_error_list


    8、hashlib

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

    def encrypt(string):
        """
        字符串加密函数
        :param string: 待加密的字符串
        :return:  返回加密过的字符串
        """
        ha = hashlib.md5(b'oldboy')
        ha.update(string.encode('utf-8'))
        result = ha.hexdigest()
        return result
    

     

    9、re

    python中re模块提供了正则表达式相关操作

     

    字符:

     

      . 匹配除换行符以外的任意字符
      w 匹配字母或数字或下划线或汉字
      s 匹配任意的空白符
      d 匹配数字
       匹配单词的开始或结束
      ^ 匹配字符串的开始
      $ 匹配字符串的结束

     

    次数:

     

      * 重复零次或更多次
      + 重复一次或更多次
      ? 重复零次或一次
      {n} 重复n次
      {n,} 重复n次或更多次
      {n,m} 重复n到m次

     

    match

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    # match,从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
     
     
     match(pattern, string, flags=0)
     # pattern: 正则模型
     # string : 要匹配的字符串
     # falgs  : 匹配模式
         X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.
         I  IGNORECASE  Perform case-insensitive matching.
         M  MULTILINE   "^" matches the beginning of lines (after a newline)
                        as well as the string.
                        "$" matches the end of lines (before a newline) as well
                        as the end of the string.
         S  DOTALL      "." matches any character at all, including the newline.
     
         A  ASCII       For string patterns, make w, W, , B, d, D
                        match the corresponding ASCII character categories
                        (rather than the whole Unicode categories, which is the
                        default).
                        For bytes patterns, this flag is the only available
                        behaviour and needn't be specified.
          
         L  LOCALE      Make w, W, , B, dependent on the current locale.
         U  UNICODE     For compatibility only. Ignored for string patterns (it
                        is the default), and forbidden for bytes patterns.
     

    search

    1
    2
    # search,浏览整个字符串去匹配第一个,未匹配成功返回None
    # search(pattern, string, flags=0)
     

    findall

    1
    2
    3
    # findall,获取非重复的匹配列表;如果有一个组则以列表形式返回,且每一个匹配均是字符串;如果模型中有多个组,则以列表形式返回,且每一个匹配均是元祖;
    # 空的匹配也会包含在结果中
    #findall(pattern, string, flags=0)
     

    sub

    1
    2
    3
    4
    5
    6
    7
    8
    # sub,替换匹配成功的指定位置字符串
     
    sub(pattern, repl, string, count=0, flags=0)
    # pattern: 正则模型
    # repl   : 要替换的字符串或可执行对象
    # string : 要匹配的字符串
    # count  : 指定匹配个数
    # flags  : 匹配模式
     

    split

    1
    2
    3
    4
    5
    6
    7
    # split,根据正则匹配分割字符串
     
    split(pattern, string, maxsplit=0, flags=0)
    # pattern: 正则模型
    # string : 要匹配的字符串
    # maxsplit:指定分割个数
    # flags  : 匹配模式

    IP:
    ^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$
    手机号:
    ^1[3|4|5|8][0-9]d{8}$
    邮箱:
    [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+ 
    
    

    10、configparser

    configparser用于处理特定格式的文件,其本质上是利用open来操作文件。

    #!/usr/bin/env python
    # Version = 3.5.2
    # __auth__ = '无名小妖'
    import configparser

    config = configparser.ConfigParser()
    config.read('ha.ini', encoding='utf-8')

    ret = config.sections() # 获取所有节点
    print(ret)

    ret = config.items('section1') # 获取指定节点下所有的键值对
    print(ret)

    ret = config.options('section1') # 获取指定节点下所有的建
    print(ret)

    v = config.get('section1', 'k1') # 获取指定节点下指定key的值
    print(v)
    # v = config.getint('section1', 'k1')
    # v = config.getfloat('section1', 'k1')
    # v = config.getboolean('section1', 'k1')

    # 检查、删除、添加节点
    # 检查
    has_sec = config.has_section('section1')
    print(has_sec)

    # 添加节点
    config.add_section("SEC_1")
    config.write(open('xxxooo', 'w'))

    # 删除节点
    config.remove_section("SEC_1")
    config.write(open('xxxooo', 'w'))

    # 检查、删除、设置指定组内的键值对
    # 检查
    has_opt = config.has_option('section1', 'k1')
    print(has_opt)

    # 删除
    config.remove_option('section1', 'k1')
    config.write(open('xxxooo', 'w'))

    # 设置
    config.set('section1', 'k10', "123")
    config.write(open('xxxooo', 'w'))
    
    

    11、requests

    import requests
    response = requests.get('http://wthrcdn.etouch.cn/weather_mini?city=北京')
    response.encoding = 'utf-8'
    print(response.text)
    IP:
    ^(25[0-5]|2[0-4]d|[0-1]?d?d)(.(25[0-5]|2[0-4]d|[0-1]?d?d)){3}$
    手机号:
    ^1[3|4|5|8][0-9]d{8}$
    邮箱:
    [a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+ 
  • 相关阅读:
    dom 获取节点练习
    dom 节点的添加删除 与修改
    dom document属性练习
    ArrayList 去除重复元素
    ud类型聊天
    UDP数据发送
    指定标签所在div在新窗口打开
    日期Calendar
    Seraph介绍
    U盘cmd命令行修复
  • 原文地址:https://www.cnblogs.com/wumingxiaoyao/p/5745970.html
Copyright © 2011-2022 走看看