python----模块知识拓展

1.hashlib ------configpraser-------- xml

hashlib 

模块导入:import hashlib

模块说明:用于将信息加密,明文变成密文

功能说明

MD5算法

m=hashlib.md5()将方法赋值给一个对象

m.update("hello world".encode("utf-8"))#需要转换成字节类型

m.hexdigest()加密后的16进制的数据

 

SHA256算法

m=hashlib.sha256()

m.update("hello world".encode("utf-8"))

m.hexdigest()#加密后的数据

注意:update的数据必须是字节类型

configparser

 

模块导入:import configparser   3.x   improot ConfigParser 2.x

模块说明:用于生成配置文件 .ini文件

功能说明

生成配置文件

Python
import configparser

config = configparser.ConfigParser()#将方法写入一个对象中
config["DEFAULT"] = {"ipaddress":"192.168.0.100","user":"root","pasw":"123","port":"3306"}
config["www.hairuinet.com"] = {"name":"hairui","index":"www.hairuinet.com"}
config["www.92hairui.cn"] ={"name":"hairui","index":"www.92hairui.com"}#创建里面section
with open("web.ini","w") as f:#写入文件
    config.write(f)


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
 

步骤:

  1. 将生成文件方法写个一个变量

  2. 在方法下创建内容

  3. 将方法内容写入文件

读取配置文件

Python
config= configparser.ConfigParser()
config.read("web.ini")
print(config.defaults())#读取的DEFAULT的信息 是个有序的字典
print(config.sections())#读取所有的section 是个列表
for i in config["www.92hairui.cn"]:#包含DEFAULT下的信息
    print(i)


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
 

defaults()是DEFAULT的信息

sections()是所有的主键值

注:config对象执行了读取操作,config对象就成了一个字典格式,按字典格式操作。

删除配置信息

Python
import configparser

#删除信息
config= configparser.ConfigParser()
config.read("web.ini")

config.remove_section("www.92hairui.cn")#删除一个section
config.remove_option("www.hairuinet.com","name")#删除一个section下的一条记录
config.write(open("web.ini","w"))#删除完毕后写入文件


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
 

remove_section(section)  删除主键下的所有

remove_option(section,option)删除section主键下的某条记录

修改配置信息

Python
import configparser

config= configparser.ConfigParser()
config.read("web.ini")
config.set("www.hairuinet.com","name","海瑞")#修改option的值
#config.add_section("www.baidu.com")#添加一个section,如果有会报错
print(config.has_section("www.92hairui.cn"))#判断一个section是否在配置文件中

config.write(open("web.ini","w"))


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
 

set()只能修改某个section的值。

注意事项:

修改和删除之后必须要重新写入,否则不生效的!

xml

模块导入:import xml.etree.ElementTree

模块说明:用于生成配置文件 .ini文件

功能说明

xml文件

Markup
<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
 

文件操作  查  改   删

Python
#!/usr/bin/env python
# -*- coding=utf-8 -*-
# Created on:  2016年12月  日
# @author: 郑建文
# blog:www.hairuinet.com
# Version: 1.0

import xml.etree.ElementTree as xml


t = xml.parse("xml_file")
tree = t.getroot()

# =======遍历文件
'''
for i in tree:
    print(i.tag,i.attrib)#country {'name': 'Liechtenstein'}
    for f in i:
        print(f.tag,f.text,)
# {'updated': 'yes'} f.attrib
# rank   f.tag
# 2 f.text
'''

#=======查找year 的 标签的tag和text

for node in tree.iter('year'):
    print(node.tag,node.text)
# 修改
for node in tree.iter('year'):
    new_year = int(node.text) + 1
    node.text = str(new_year)
    node.set("updated", "yes")

tree.write("xmltest.xml")

# 删除node
for country in tree.findall('country'):
    rank = int(country.find('rank').text)
    if rank > 50:
        tree.remove(country)

tree.write('output.xml')


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
 

创建xml文件

Python
import xml.etree.ElementTree as ET

new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
sex = ET.SubElement(name, "sex")
sex.text = '33'
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age = ET.SubElement(name2, "age")
age.text = '19'
#以下写入文件固定格式
et = ET.ElementTree(new_xml)  # 生成文档对象
et.write("test.xml", encoding="utf-8", xml_declaration=True)

2.logging------ json -------picle -------shelve

logging

导入方式: import loggin

模块用途:用于写日志功能模块

功能介绍

默认情况下,logging将日志打印到屏幕,日志级别为WARNING;

日志级别大小关系为:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,当然也可以自己定义日志级别。

 

Python
import logging

logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s] [%(filename)s][line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%F %T',
                    filename='myapp.log',
                    filemode='w')

logging.debug('debug 信息')
logging.info('INFO 信息')
logging.warning('警告信息')

#[2016-12-10 14:12:37] [randommk.py][line:53] DEBUG debug 信息
#[2016-12-10 14:12:37] [randommk.py][line:54] INFO INFO 信息
#[2016-12-10 14:12:37] [randommk.py][line:55] WARNING 警告信息


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161240/index.html
 

level=logging.DEBUG 设置日志级别

format 设置输出格式

    %(levelno)s: 打印日志级别的数值
     %(levelname)s: 打印日志级别名称
     %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
     %(filename)s: 打印当前执行程序名
     %(funcName)s: 打印日志的当前函数
     %(lineno)d: 打印日志的当前行号
     %(asctime)s: 打印日志的时间
     %(thread)d: 打印线程ID
     %(threadName)s: 打印线程名称
     %(process)d: 打印进程ID
     %(message)s: 打印日志信息

datefmt 设置日期格式,同 time.strftime()

      %Y 年 %m 月  %D日  %H时  %M分  %S 秒

filename 设置文件路径

filemode 设置文件打开模式 

注:没有filename和filemode直接输出

屏幕和文件同时输出和写入

Python
import logging

logger = logging.getLogger()# 创建一个handler,用于写入日志文件fh = logging.FileHandler('test.log')# 再创建一个handler,用于输出到控制台ch = logging.StreamHandler()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
logger.addHandler(ch)

logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161240/index.html
 

json

导入方式: import json

模块用途:json,用于字符串 和 python数据类型间进行转换,和其他语言交换数据

功能介绍

dumps 将字符串通过特殊方法转换成python认识的格式,如字符串转字典啥的

Python
li = "[1,2,3]"
s = json.loads(li)
print(type(s))


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161240/index.html
 

dump 将数据类型通过特殊方法转换成json格式,并存入文件中,加了一个write的操作

loads 将json的字符串转换成python的数据类型

load将字符串通过特殊方法转换成python认识的格式,并存入文件中,加了一个read的操作

注:操作文件必须先写文件句柄,将所有单引号变双引号

picle

导入方式: import picle

模块用途:pickle,用于python特有的类型只能和python的数据类型间进行转换

功能介绍

同json

 

shelve

导入方式: import shelve

模块用途:pickle的高级版本,只有一个写法,会生成3个文件

功能介绍

f = shelve.open(r"文件路径")

f = []

f["key"] = {...}


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161240/index.html

3.time------ datetime------ random

time

导入方式:import time

模块用途:对时间的操作

功能说明

时间戳                  1970年1月1日之后的秒,即:time.time()

格式化的字符串    2014-11-11 11:11,    即:time.strftime('%Y-%m-%d')

结构化时间           元组包含了:年、日、星期等... time.struct_time    即:time.localtime()

print(time.time()) 打印当前时间戳

print(time.ctime())  # 返回Fri Aug 19 12:38:29 2016 格式, 可以加参数,比如time.ctime(time.time()-86400) 前一天

print(time.gmtime())#返回当前信息的变量值,时间为时区格林时间

Python
#time.struct_time(tm_year=2016, tm_mon=12, tm_mday=9, tm_hour=5, tm_min=11, tm_sec=37, tm_wday=4, tm_yday=344, tm_isdst=0)print(time.gmtime())time1 = time.gmtime(time.time()+28800)#+8个小时print("%d-%d-%d %d:%d:%d"%(time1.tm_year,time1.tm_mon,time1.tm_mday,time1.tm_hour,time1.tm_min,time1.tm_sec))


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161239/index.html
 

 

print(time.clock())  # 返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来

print(time.altzone)  # 返回与utc时间的时间差,以秒计算

print(time.asctime())  # 返回时间格式"Fri Aug 19 11:14:16 2016",

print(time.localtime())  # 返回本地时间 的struct time对象格式

print(time.gmtime(time.time() - 800000))  # 返回utc时间的struc时间对象格式

struct_2_stamp = time.mktime(string_2_struct)  # 将struct时间对象转成时间戳

#将时间戳转为字符串格式

print(time.gmtime(time.time() - 86640))  # 将utc时间戳转换成struct_time格式

print(time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()))  # 将utc struct_time格式转成指定的字符串格式

 

print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式

print(time.strftime("%F  %T",time.gmtime()) ) 和上面结果一样

time.strftime()的格式说明

    %a 星期几的简写
    %A 星期几的全称
    %b 月分的简写
    %B 月份的全称
    %c 标准的日期的时间串
    %C 年份的后两位数字
    %d 十进制表示的每月的第几天
    %D 月/天/年
    %e 在两字符域中,十进制表示的每月的第几天
    %F 年-月-日
    %g 年份的后两位数字,使用基于周的年
    %G 年分,使用基于周的年
    %h 简写的月份名
    %H 24小时制的小时
   %I 12小时制的小时

    %j 十进制表示的每年的第几天
    %m 十进制表示的月份
    %M 十时制表示的分钟数
    %n 新行符
    %p 本地的AM或PM的等价显示
    %r 12小时的时间
    %R 显示小时和分钟:hh:mm
    %S 十进制的秒数
    %t 水平制表符
    %T 显示时分秒:hh:mm:ss
    %u 每周的第几天,星期一为第一天 (值从0到6,星期一为0)
    %U 第年的第几周,把星期日做为第一天(值从0到53)
    %V 每年的第几周,使用基于周的年
    %w 十进制表示的星期几(值从0到6,星期天为0)
    %W 每年的第几周,把星期一做为第一天(值从0到53)
    %x 标准的日期串
    %X 标准的时间串
    %y 不带世纪的十进制年份(值从0到99)
    %Y 带世纪部分的十制年份
    %z,%Z 时区名称,如果不能得到时区名称则返回空字符。
    %% 百分号

datatime

导入方式:

模块用途:时间模块

功能说明

print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925

print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19

print(datetime.datetime.now() )

print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天

print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天

print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时

print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分

random

导入方式:import random

模块用途:用于生成随机数

功能说明

print(random.random())#随机生成一个小数
print(random.randint(1,5))#生成1-4 随机一个
print(random.randrange(10))#生成0-9 随机一个

print(random.randrange(10,21))#生成10-21 随机一个

案例:随机验证码

Python
#!/usr/bin/env python# -*- coding=utf-8 -*-# Created on:  2016年12月 9日# @author: 郑建文# Email: 574601624@qq.com# Version: 1.0import randomyzm = ""for i in range(6):    a = random.randrange(4)    if a == 1 or a == 3:        yzm += str(a)    else:        b = random.randrange(65, 91)        s = chr(b)        yzm += sprint(yzm)


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161239/index.html
 

案例:随机颜色

Python
#!/usr/bin/env python# -*- coding=utf-8 -*-# Created on:  2016年12月  日# @author: 郑建文# Email: 574601624@qq.com# Version: 1.0import randomfor i in range(10):    x = random.randrange(30,38)    print("33[{0};1m我的颜色编号为:33[1m{0}".format(x))


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161239/index.html
 

calendar

导入方式:import calendar

模块用途:用于读取某年某一月的信息,也是时间模块

功能说明

calendar.month(年,月)获取当前月的日历格式

Python
import calendars = calendar.month(2016,12)print(s)


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161239/index.html
 
序号函数及描述
1 calendar.calendar(year,w=2,l=1,c=6)
返回一个多行字符串格式的year年年历,3个月一行,间隔距离为c。 每日宽度间隔为w字符。每行长度为21* W+18+2* C。l是每星期行数。
2 calendar.firstweekday( )
返回当前每周起始日期的设置。默认情况下,首次载入caendar模块时返回0,即星期一。
3 calendar.isleap(year)
是闰年返回True,否则为false。
4 calendar.leapdays(y1,y2)
返回在Y1,Y2两年之间的闰年总数。
5 calendar.month(year,month,w=2,l=1)
返回一个多行字符串格式的year年month月日历,两行标题,一周一行。每日宽度间隔为w字符。每行的长度为7* w+6。l是每星期的行数。
6 calendar.monthcalendar(year,month)
返回一个整数的单层嵌套列表。每个子列表装载代表一个星期的整数。Year年month月外的日期都设为0;范围内的日子都由该月第几日表示,从1开始。
7 calendar.monthrange(year,month)
返回两个整数。第一个是该月的星期几的日期码,第二个是该月的日期码。日从0(星期一)到6(星期日);月从1到12。
8 calendar.prcal(year,w=2,l=1,c=6)
相当于 print calendar.calendar(year,w,l,c).
9 calendar.prmonth(year,month,w=2,l=1)
相当于 print calendar.calendar(year,w,l,c)。
10 calendar.setfirstweekday(weekday)
设置每周的起始日期码。0(星期一)到6(星期日)。
11 calendar.timegm(tupletime)
和time.gmtime相反:接受一个时间元组形式,返回该时刻的时间辍(1970纪元后经过的浮点秒数)。
12 calendar.weekday(year,month,day)
返回给定日期的日期码。0(星期一)到6(星期日)。月份为 1(一月) 到 12(12月)。

 


4.sys ------os------- getpass

模块的导入

导入一个py文件,解释器解释该py文件

导入一个包,解释器解释该包下的 __init__.py 文件

 

import module  直接导入模块

from module.xx.xx import xx  从某个模块包导入某个模块

from module.xx.xx import xx as rename   从某个包导入模块并给起个别名

from module.xx.xx import * 从某个包导入该包下所有模块

模块安装

第一种

 

    yum install 模块名称

    pip install 模块名称

    pip3  install 模块名称

    apt-get

第二种

    下载源码

    解压源码

    进入目录

    编译源码    python setup.py build

    安装源码    python setup.py install

sys模块

导入方式: import sys

模块用途:调取系统信息

功能介绍

sys.argv           命令行参数List,第一个元素是程序本身路径  执行  a.py a b c    # ["a.py","a","b", "c"]

sys.exit(n)        退出程序,正常退出时exit(0)  0-127  默认为0

sys.version        获取Python解释程序的版本信息

sys.maxint         最大的Int值

sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 

sys.platform       返回操作系统平台名称 如:win32 win64 .. 用于跨平台

sys.stdout.write('please:') 标准化输入

val = sys.stdin.readline()[:-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所指向的文件或者目录的最后修改时间

os.getpid() 获取进程的pid

os.getppid() 获取父进程的pid

 

subprocess

导入方式:import subproess

模块功能:执行用户命令

功能介绍

s = subproess.Popen(命令,shell=True,stdout=subproess.PIPE)执行命令将结果反正stdout里

s.stdout.read().encode()将结果读取并解码

getpass模块

导入方式:import getpass

模块用途:将用户输入的信息变成密文模式

功能介绍

getpass.getpass(">>") 等待用户输入,用户无法看到输入内容

 

1.安装模块

1)利用pip安装

    pip install 模块名

2)利用源码安装

    python setup.py install

2.卸载模块

1).如果是用pip安装的,可以直接使用pip uninstall 模块名

2).如果是用python setup.py install安装,使用python setup.py uninstall来卸载

   例如:pip uninstall pyserial

 


#本段代码来自 海瑞博客http://www.hairuinet.com/python/20161241/index.html
原文地址:https://www.cnblogs.com/xuaijun/p/7263169.html