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

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

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

模块分为三种:

  • 自定义模块

  • 第三方模块

  • 内置模块

1、定义模块

情景一:

  

情景二:

  

情景三:

  

2、导入模块

  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 *

导入模块其实就是告诉Python解释器去解释那个py文件

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

  • 导入一个包,解释器解释该包下的 __init__.py 文件 【py2.7】

那么问题来了,导入模块时是根据那个路径作为基准来进行的呢?即:sys.path

  1. import sys
  2. print(sys.path)
  3.  
  4. 结果:['', 'C:\\Windows\\SYSTEM32\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Users\\admin\\AppData\\Roaming\\Python\\Python34\\site-packages', 'C:\\Python34\\lib\\site-packages']
  5.  
  6. # sys.path 第一个值为当前路径
  7. # site-packages 存放所有第三方安装的模块

  如果sys.path路径列表没有你想要的路径,可以通过 sys.path.append('路径') 添加。

  1. import sys
  2. import os
  3. project_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  4. sys.path.append(project_path)
  5.  
  6. 或者:
  7. sys.path.append("D:")

  例子:

  1. # 导入全部内容
  2. import s1
  3.  
  4. # 导入函数f1
  5. from s1 import f1
  6. f1()
  7.  
  8. ***************************
  9. # lib 包名
  10. # 导入lib 下的account.py 中的login函数
  11. from lib.account import login
  12. login()
  13.  
  14. # 方法二:
  15. from lib import account
  16. account.login()
  17.  
  18. # 方法三:
  19. import lib.account
  20. lib.account.login()
  21.  
  22. ***************************
  23. # 别名
  24. from lib import account as BBB
  25. BBB.login()

模块

内置模块是Python自带的功能,在使用内置模块相应的功能时,需要【先导入】再【使用】

一、sys

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

  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 返回操作系统平台名称,如win32
  7. sys.stdin 输入相关
  8. sys.stdout 输出相关
  9. sys.stderror 错误相关
  10.  
  11. sys.stdout.flush() 强制刷新到屏幕
  12. sys.stdout.write("\r") 每一次清空原行
  13.  
  14. sys.stdout.write("hello") 输出后 没有换行
  15. print() 自动换行
  1. #!/usr/bin/env python
  2. # -*-coding:utf-8 -*-
  3.  
  4. import sys
  5. import time
  6.  
  7. for i in range(1,101):
  8. sys.stdout.write('\r')
  9. sys.stdout.write(' %i%% %s'%(i,i*'#'))
  10. sys.stdout.flush()
  11. time.sleep(0.1)
  12.  
  13. sys.stdout.flush() 强制刷新到屏幕
  14. sys.stdout.write("\r") 每一次清空原行
  15. %% 防止转义

进度条百分比

二、os

用于提供系统级别的操作:

  1. os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
  2. os.chdir("dirname") 改变当前脚本工作目录;相当于shellcd
  3. os.curdir 返回当前目录: ('.')
  4. os.pardir 获取当前目录的父目录字符串名:('..')
  5. os.makedirs('dir1/dir2') 可生成多层递归目录,存在则报错
  6. os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推,只删除空文件夹
  7. os.mkdir('dirname') 生成单级目录;相当于shellmkdir dirname
  8. os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shellrmdir dirname
  9. os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
  10. os.remove() 删除一个文件
  11. os.rename("oldname","new") 重命名文件/目录
  12. os.stat('path/filename') 获取文件/目录信息
  13. os.sep 操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
  14. os.linesep 当前平台使用的行终止符,win下为"\r\n",Linux下为"\n"
  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所指向的文件或者目录的最后修改时间

  例子:

  1. import os
  2.  
  3. # os.path.exists 如果path存在,返回True;如果path不存在,返回False
  4. bool_path = os.path.exists("D://123")
  5. print(bool_path)
  6. # False
  7.  
  8. # os.path.dirname 返回path的目录。其实就是os.path.split(path)的第一个元素
  9. dir_path = os.path.dirname("D:\Youdao\YoudaoNote")
  10. print(dir_path)
  11. # D:\Youdao
  12.  
  13. # os.path.join 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
  14. name_path = os.path.join('D:\yy','tt.txt')
  15. print(name_path)
  16. # D:\yy\tt.txt
  17.  
  18. # os.stat('path/filename|dirname') 获取文件/目录信息
  19. st = os.stat('D:\yy\Launcher.xml')
  20. print(st)
  21. # os.stat_result(st_mode=33206, st_ino=2814749767142260, st_dev=1726123312, st_nlink=1, st_uid=0, st_gid=0, st_size=209, st_atime=1457605409, st_mtime=1470828693, st_ctime=1457605409)

三、time

时间相关的操作,时间有三种表示方式:

  • 时间戳               从1970年1月1日到现在一共过去了多少秒,即:time.time()

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

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

常用方法:

  1. print(time.time()) # 返回当前系统时间戳
  2.  
  3. print(time.clock()) # 计算cpu执行时间
  4.  
  5. print(time.gmtime()) # UTC时间,结构化tuple
  6. print(time.localtime()) # 本地时间,结构化tuple
  7.  
  8. print(time.strftime(format,tuple)) # format格式 : %Y:%m:%d %H:%M:%S , tuple:结构化时间
  9. print(time.strptime(string time,format)) # string time 对应的format格式 , 返回结构化时间
  10.  
  11. print(time.ctime(时间戳)) # 时间戳 => string , Sat Nov 26 19:49:21 2016 ,当前系统时间
  12. print(time.mktime(tuple)) # 结构化时间tuple => 时间戳

 时间戳 => 时间数组(结构化时间):

  1. import time
  2. print( time.localtime(时间戳) ) # 时间戳 float类型 => 结构化时间,tuple
  3.  
  4. import datetime
  5. print( datetime.datetime.fromtimestamp(时间戳) ) # 时间戳float => datetime.datetime

datetime => time 结构化时间

  1. datetime对象.timetuple()

时间加减:

  1. print(datetime.datetime.now()) #返回 2016-11-26 20:04:32.586288
  2. print(datetime.datetime.fromtimestamp(time.time()) ) # 时间戳直接转成日期格式 2016-11-26
  3. print(datetime.datetime.now() + datetime.timedelta(3)) # 当前时间+3天
  4. print(datetime.datetime.now() + datetime.timedelta(-3)) # 当前时间-3天
  5. print(datetime.datetime.now() + datetime.timedelta(hours=3)) # 当前时间+3小时
  6. print(datetime.datetime.now() + datetime.timedelta(weeks=1)) # 当前时间+1周
  7.  
  8. # timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
  9.  
  10. c_time = datetime.datetime.now()
  11. print(c_time.replace(minute=3,hour=2)) #时间替换

关系转换例子

datetime <=> string

  datetime -> string

  1. datetime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  2. print(datetime)
  3.  
  4. # 2016-11-26 20:20:20

  string -> datetime

  1. datetime.datetime.strptime("2016-11-26 20:20:20", "%Y-%m-%d %H:%M:%S")

datetime <=> date

  datetime -> date

  1. datetime.datetime.now().date()

  date -> datetime

  1. today = datetime.date.today()
  2. datetime = datetime.datetime.combine(today, datetime.time())

四、序列化

Python中用于序列化的两个模块

  • json     只能序列化 列表,变量,字符串,字典

  • pickle   可以序列化 任何类型  因为只有python支持

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

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

  1. Functions:
  2.  
  3. dump(object, file)
  4. dumps(object) -> string
  5. load(file) -> object
  6. loads(string) -> object
  7.  
  8. *************************************
  9.  
  10. import pickle
  11.  
  12. data = { 'name' : 'alex' ,'age' : 18 }
  13.  
  14. # pickle.dumps 将数据通过特殊的形式转换为只有python语言认识的字符串
  15. p_str = pickle.dumps(data)
  16. print(p_str)
  17.  
  18. # pickle.dump 将数据通过特殊的形式转换为只有python语言认识的字符串,并写入文件
  19. with open('ab.txt','wb')as f:
  20. pickle.dump(data,f)
  21.  
  22. # 从文件中读取
  23. with open('ab.txt','rb')as f:
  24. data = pickle.load(f)
  25. print(data)
  26.  
  27. ************************************
  28.  
  29. import json
  30.  
  31. # json.dumps 将python基本数据类型 => 将字符串
  32. # 将数据通过特殊的形式转换为所有语言都认识的字符串
  33.  
  34. j_str = json.dumps(data)
  35. print(j_str)
  36.  
  37. # json.loads 将字符串 => python基本数据类型
  38. # 用于将字典,列表,元组形式的字符串 装换成 字典,列表,元组
  39. # 注意: 如果 字典内的元素 是字符串要用双引号! ,
  40. list_str = '[11,22,33,44]'
  41. dic_str = '{"v1":"k1","v2":"k2"}'
  42. json.loads(dic_str)
  43.  
  44. # json.dump 将数据通过特殊的形式转换为所有语言都认识的字符串,并写入文件
  45. with open('js.txt','w')as f:
  46. json.dump(data,f)
  47.  
  48. dic = { 'k1':123 , 'k2' : 'v2' }
  49. json.dump(dic,open('db','w'))
  50.  
  51. # 从文件中读取
  52. with open('js.txt', 'r')as f:
  53. data = json.load(f)
  54. print(data)
  55.  
  56. r = json.load(open('db','r'))
  57. print(r,type(r))

五、hashlib

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

  1. import md5
  2. hash = md5.new()
  3. hash.update('admin')
  4. print hash.hexdigest()

md5-废弃

  1. import sha
  2.  
  3. hash = sha.new()
  4. hash.update('admin')
  5. print hash.hexdigest()

sha-废弃

  1. import hashlib
  2.  
  3. # ######## md5 ########
  4. hash = hashlib.md5()
  5. # help(hash.update)
  6. hash.update(bytes('admin', encoding='utf-8')) # (方法一) update() 接收二进制类型 / 同一对象,连续两次不同值的update 等于拼接!!
    hash.update('admin'.encode('utf8)) # (方法二) 转换成二进制形式
  7. print(hash.hexdigest()) # 16进制方式表示
  8.  
  9. ######## sha1 ########
  10.  
  11. hash = hashlib.sha1()
  12. hash.update(bytes('admin', encoding='utf-8'))
  13. print(hash.hexdigest())
  14.  
  15. # ######## sha256 ########
  16.  
  17. hash = hashlib.sha256()
  18. hash.update(bytes('admin', encoding='utf-8'))
  19. print(hash.hexdigest())
  20.  
  21. # ######## sha384 ########
  22.  
  23. hash = hashlib.sha384()
  24. hash.update(bytes('admin', encoding='utf-8'))
  25. print(hash.hexdigest())
  26.  
  27. # ######## sha512 ########
  28.  
  29. hash = hashlib.sha512()
  30. hash.update(bytes('admin', encoding='utf-8'))
  31. print(hash.hexdigest())

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

  1. import hashlib
  2.  
  3. # ######## md5 ########
  4.  
  5. hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
  6. hash.update(bytes('admin',encoding="utf-8"))
  7. print(hash.hexdigest())

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

  1. import hmac
  2.  
  3. h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
  4. h.update(bytes('admin',encoding="utf-8"))
  5. print(h.hexdigest())

登录与注册

、requests

  Python标准库中提供了:urllib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

  1. import urllib.request
  2.  
  3. f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
  4. result = f.read().decode('utf-8')

发送GET请求

  1. import urllib.request
  2.  
  3. req = urllib.request.Request('http://www.example.com/')
  4. req.add_header('Referer', 'http://www.python.org/')
  5. r = urllib.request.urlopen(req)
  6.  
  7. result = f.read().decode('utf-8')

发送携带请求头的GET请求

注:更多见Python官方文档:https://docs.python.org/3.5/library/urllib.request.html#module-urllib.request

  Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。

  1. response = requests.get('http://www.baidu.com')
  2. response.encoding = 'utf-8'  # 注意编码问题
  3. result = response.text
  4. print(result)

1、安装模块

  1. pip3 install requests

2、使用模块

  1. # 1、无参数实例
  2.  
  3. import requests
  4.  
  5. ret = requests.get('https://github.com/timeline.json')
  6.  
  7. print(ret.url)
  8. print(ret.text)
  9.  
  10. # 2、有参数实例
  11.  
  12. import requests
  13.  
  14. payload = {'key1': 'value1', 'key2': 'value2'}
  15. ret = requests.get("http://httpbin.org/get", params=payload)
  16.  
  17. print(ret.url)
  18. print(ret.text)

GET请求

  1. # 1、基本POST实例
  2.  
  3. import requests
  4.  
  5. payload = {'key1': 'value1', 'key2': 'value2'}
  6. ret = requests.post("http://httpbin.org/post", data=payload)
  7.  
  8. print(ret.text)
  9.  
  10. # 2、发送请求头和数据实例
  11.  
  12. import requests
  13. import json
  14.  
  15. url = 'https://api.github.com/some/endpoint'
  16. payload = {'some': 'data'}
  17. headers = {'content-type': 'application/json'}
  18.  
  19. ret = requests.post(url, data=json.dumps(payload), headers=headers)
  20.  
  21. print(ret.text)
  22. print(ret.cookies)

POST请求

  1. requests.get(url, params=None, **kwargs)
  2. requests.post(url, data=None, json=None, **kwargs)
  3. requests.put(url, data=None, **kwargs)
  4. requests.head(url, **kwargs)
  5. requests.delete(url, **kwargs)
  6. requests.patch(url, data=None, **kwargs)
  7. requests.options(url, **kwargs)
  8.  
  9. # 以上方法均是在此方法的基础上构建
  10. requests.request(method, url, **kwargs)

其他请求

更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/

3、Http请求和XML实例

实例:检测QQ账号是否在线

  1. import urllib
  2. import requests
  3. from xml.etree import ElementTree as ET
  4.  
  5. # 使用内置模块urllib发送HTTP请求,或者XML格式内容
  6. """
  7. f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
  8. result = f.read().decode('utf-8')
  9. """
  10.  
  11. # 使用第三方模块requests发送HTTP请求,或者XML格式内容
  12. r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
  13. result = r.text
  14.  
  15. # 解析XML格式内容
  16. node = ET.XML(result)
  17.  
  18. # 获取内容
  19. if node.text == "Y":
  20. print("在线")
  21. else:
  22. print("离线")

实例:查看火车停靠信息

  1. import urllib
  2. import requests
  3. from xml.etree import ElementTree as ET
  4.  
  5. # 使用内置模块urllib发送HTTP请求,或者XML格式内容
  6. """
  7. f = urllib.request.urlopen('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
  8. result = f.read().decode('utf-8')
  9. """
  10.  
  11. # 使用第三方模块requests发送HTTP请求,或者XML格式内容
  12. r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
  13. result = r.text
  14.  
  15. # 解析XML格式内容
  16. root = ET.XML(result)
  17. for node in root.iter('TrainDetailInfo'):
  18. print(node.find('TrainStation').text,node.find('StartTime').text,node.tag,node.attrib)

注:更多接口猛击这里

七、XML

XML是实现不同语言或程序之间进行数据交换的协议,XML文件格式如下:

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

1、解析XML

  1. from xml.etree import ElementTree as ET
  2.  
  3. # 打开文件,读取XML内容
  4. str_xml = open('xo.xml', 'r').read()
  5.  
  6. # 将字符串解析成xml特殊对象,root代指xml文件的根节点
  7. root = ET.XML(str_xml)

ElementTree.XML将字符串解析成xml对象

  1. from xml.etree import ElementTree as ET
  2.  
  3. # 直接解析xml文件
  4. tree = ET.parse("xo.xml")
  5.  
  6. # 获取xml文件的根节点
  7. root = tree.getroot()

ElementTree.parse将字符串解析成xml对象

2、操作XML

XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:

  1. class Element:
  2. """An XML element.
  3.  
  4. This class is the reference implementation of the Element interface.
  5.  
  6. An element's length is its number of subelements. That means if you
  7. want to check if an element is truly empty, you should check BOTH
  8. its length AND its text attribute.
  9.  
  10. The element tag, attribute names, and attribute values can be either
  11. bytes or strings.
  12.  
  13. *tag* is the element name. *attrib* is an optional dictionary containing
  14. element attributes. *extra* are additional element attributes given as
  15. keyword arguments.
  16.  
  17. Example form:
  18. <tag attrib>text<child/>...</tag>tail
  19.  
  20. """
  21.  
  22. 当前节点的标签名
  23. tag = None
  24. """The element's name."""
  25.  
  26. 当前节点的属性
  27.  
  28. attrib = None
  29. """Dictionary of the element's attributes."""
  30.  
  31. 当前节点的内容
  32. text = None
  33. """
  34. Text before first subelement. This is either a string or the value None.
  35. Note that if there is no text, this attribute may be either
  36. None or the empty string, depending on the parser.
  37.  
  38. """
  39.  
  40. tail = None
  41. """
  42. Text after this element's end tag, but before the next sibling element's
  43. start tag. This is either a string or the value None. Note that if there
  44. was no text, this attribute may be either None or an empty string,
  45. depending on the parser.
  46.  
  47. """
  48.  
  49. def __init__(self, tag, attrib={}, **extra):
  50. if not isinstance(attrib, dict):
  51. raise TypeError("attrib must be dict, not %s" % (
  52. attrib.__class__.__name__,))
  53. attrib = attrib.copy()
  54. attrib.update(extra)
  55. self.tag = tag
  56. self.attrib = attrib
  57. self._children = []
  58.  
  59. def __repr__(self):
  60. return "<%s %r at %#x>" % (self.__class__.__name__, self.tag, id(self))
  61.  
  62. def makeelement(self, tag, attrib):
  63. 创建一个新节点
  64. """Create a new element with the same type.
  65.  
  66. *tag* is a string containing the element name.
  67. *attrib* is a dictionary containing the element attributes.
  68.  
  69. Do not call this method, use the SubElement factory function instead.
  70.  
  71. """
  72. return self.__class__(tag, attrib)
  73.  
  74. def copy(self):
  75. """Return copy of current element.
  76.  
  77. This creates a shallow copy. Subelements will be shared with the
  78. original tree.
  79.  
  80. """
  81. elem = self.makeelement(self.tag, self.attrib)
  82. elem.text = self.text
  83. elem.tail = self.tail
  84. elem[:] = self
  85. return elem
  86.  
  87. def __len__(self):
  88. return len(self._children)
  89.  
  90. def __bool__(self):
  91. warnings.warn(
  92. "The behavior of this method will change in future versions. "
  93. "Use specific 'len(elem)' or 'elem is not None' test instead.",
  94. FutureWarning, stacklevel=2
  95. )
  96. return len(self._children) != 0 # emulate old behaviour, for now
  97.  
  98. def __getitem__(self, index):
  99. return self._children[index]
  100.  
  101. def __setitem__(self, index, element):
  102. # if isinstance(index, slice):
  103. # for elt in element:
  104. # assert iselement(elt)
  105. # else:
  106. # assert iselement(element)
  107. self._children[index] = element
  108.  
  109. def __delitem__(self, index):
  110. del self._children[index]
  111.  
  112. def append(self, subelement):
  113. 为当前节点追加一个子节点
  114. """Add *subelement* to the end of this element.
  115.  
  116. The new element will appear in document order after the last existing
  117. subelement (or directly after the text, if it's the first subelement),
  118. but before the end tag for this element.
  119.  
  120. """
  121. self._assert_is_element(subelement)
  122. self._children.append(subelement)
  123.  
  124. def extend(self, elements):
  125. 为当前节点扩展 n 个子节点
  126. """Append subelements from a sequence.
  127.  
  128. *elements* is a sequence with zero or more elements.
  129.  
  130. """
  131. for element in elements:
  132. self._assert_is_element(element)
  133. self._children.extend(elements)
  134.  
  135. def insert(self, index, subelement):
  136. 在当前节点的子节点中插入某个节点,即:为当前节点创建子节点,然后插入指定位置
  137. """Insert *subelement* at position *index*."""
  138. self._assert_is_element(subelement)
  139. self._children.insert(index, subelement)
  140.  
  141. def _assert_is_element(self, e):
  142. # Need to refer to the actual Python implementation, not the
  143. # shadowing C implementation.
  144. if not isinstance(e, _Element_Py):
  145. raise TypeError('expected an Element, not %s' % type(e).__name__)
  146.  
  147. def remove(self, subelement):
  148. 在当前节点在子节点中删除某个节点
  149. """Remove matching subelement.
  150.  
  151. Unlike the find methods, this method compares elements based on
  152. identity, NOT ON tag value or contents. To remove subelements by
  153. other means, the easiest way is to use a list comprehension to
  154. select what elements to keep, and then use slice assignment to update
  155. the parent element.
  156.  
  157. ValueError is raised if a matching element could not be found.
  158.  
  159. """
  160. # assert iselement(element)
  161. self._children.remove(subelement)
  162.  
  163. def getchildren(self):
  164. 获取所有的子节点(废弃)
  165. """(Deprecated) Return all subelements.
  166.  
  167. Elements are returned in document order.
  168.  
  169. """
  170. warnings.warn(
  171. "This method will be removed in future versions. "
  172. "Use 'list(elem)' or iteration over elem instead.",
  173. DeprecationWarning, stacklevel=2
  174. )
  175. return self._children
  176.  
  177. def find(self, path, namespaces=None):
  178. 获取第一个寻找到的子节点
  179. """Find first matching element by tag name or path.
  180.  
  181. *path* is a string having either an element tag or an XPath,
  182. *namespaces* is an optional mapping from namespace prefix to full name.
  183.  
  184. Return the first matching element, or None if no element was found.
  185.  
  186. """
  187. return ElementPath.find(self, path, namespaces)
  188.  
  189. def findtext(self, path, default=None, namespaces=None):
  190. 获取第一个寻找到的子节点的内容
  191. """Find text for first matching element by tag name or path.
  192.  
  193. *path* is a string having either an element tag or an XPath,
  194. *default* is the value to return if the element was not found,
  195. *namespaces* is an optional mapping from namespace prefix to full name.
  196.  
  197. Return text content of first matching element, or default value if
  198. none was found. Note that if an element is found having no text
  199. content, the empty string is returned.
  200.  
  201. """
  202. return ElementPath.findtext(self, path, default, namespaces)
  203.  
  204. def findall(self, path, namespaces=None):
  205. 获取所有的子节点
  206. """Find all matching subelements by tag name or path.
  207.  
  208. *path* is a string having either an element tag or an XPath,
  209. *namespaces* is an optional mapping from namespace prefix to full name.
  210.  
  211. Returns list containing all matching elements in document order.
  212.  
  213. """
  214. return ElementPath.findall(self, path, namespaces)
  215.  
  216. def iterfind(self, path, namespaces=None):
  217. 获取所有指定的节点,并创建一个迭代器(可以被for循环)
  218. """Find all matching subelements by tag name or path.
  219.  
  220. *path* is a string having either an element tag or an XPath,
  221. *namespaces* is an optional mapping from namespace prefix to full name.
  222.  
  223. Return an iterable yielding all matching elements in document order.
  224.  
  225. """
  226. return ElementPath.iterfind(self, path, namespaces)
  227.  
  228. def clear(self):
  229. 清空节点
  230. """Reset element.
  231.  
  232. This function removes all subelements, clears all attributes, and sets
  233. the text and tail attributes to None.
  234.  
  235. """
  236. self.attrib.clear()
  237. self._children = []
  238. self.text = self.tail = None
  239.  
  240. def get(self, key, default=None):
  241. 获取当前节点的属性值
  242. """Get element attribute.
  243.  
  244. Equivalent to attrib.get, but some implementations may handle this a
  245. bit more efficiently. *key* is what attribute to look for, and
  246. *default* is what to return if the attribute was not found.
  247.  
  248. Returns a string containing the attribute value, or the default if
  249. attribute was not found.
  250.  
  251. """
  252. return self.attrib.get(key, default)
  253.  
  254. def set(self, key, value):
  255. 为当前节点设置属性值
  256. """Set element attribute.
  257.  
  258. Equivalent to attrib[key] = value, but some implementations may handle
  259. this a bit more efficiently. *key* is what attribute to set, and
  260. *value* is the attribute value to set it to.
  261.  
  262. """
  263. self.attrib[key] = value
  264.  
  265. def keys(self):
  266. 获取当前节点的所有属性的 key
  267.  
  268. """Get list of attribute names.
  269.  
  270. Names are returned in an arbitrary order, just like an ordinary
  271. Python dict. Equivalent to attrib.keys()
  272.  
  273. """
  274. return self.attrib.keys()
  275.  
  276. def items(self):
  277. 获取当前节点的所有属性值,每个属性都是一个键值对
  278. """Get element attributes as a sequence.
  279.  
  280. The attributes are returned in arbitrary order. Equivalent to
  281. attrib.items().
  282.  
  283. Return a list of (name, value) tuples.
  284.  
  285. """
  286. return self.attrib.items()
  287.  
  288. def iter(self, tag=None):
  289. 在当前节点的子孙中根据节点名称寻找所有指定的节点,并返回一个迭代器(可以被for循环)。
  290. """Create tree iterator.
  291.  
  292. The iterator loops over the element and all subelements in document
  293. order, returning all elements with a matching tag.
  294.  
  295. If the tree structure is modified during iteration, new or removed
  296. elements may or may not be included. To get a stable set, use the
  297. list() function on the iterator, and loop over the resulting list.
  298.  
  299. *tag* is what tags to look for (default is to return all elements)
  300.  
  301. Return an iterator containing all the matching elements.
  302.  
  303. """
  304. if tag == "*":
  305. tag = None
  306. if tag is None or self.tag == tag:
  307. yield self
  308. for e in self._children:
  309. yield from e.iter(tag)
  310.  
  311. # compatibility
  312. def getiterator(self, tag=None):
  313. # Change for a DeprecationWarning in 1.4
  314. warnings.warn(
  315. "This method will be removed in future versions. "
  316. "Use 'elem.iter()' or 'list(elem.iter())' instead.",
  317. PendingDeprecationWarning, stacklevel=2
  318. )
  319. return list(self.iter(tag))
  320.  
  321. def itertext(self):
  322. 在当前节点的子孙中根据节点名称寻找所有指定的节点的内容,并返回一个迭代器(可以被for循环)。
  323. """Create text iterator.
  324.  
  325. The iterator loops over the element and all subelements in document
  326. order, returning all inner text.
  327.  
  328. """
  329. tag = self.tag
  330. if not isinstance(tag, str) and tag is not None:
  331. return
  332. if self.text:
  333. yield self.text
  334. for e in self:
  335. yield from e.itertext()
  336. if e.tail:
  337. yield e.tail
  338.  
  339. 节点功能一览表

功能节点一览

由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so   可以利用以上方法进行操作xml文件。

a. 遍历XML文档的所有内容

  1. from xml.etree import ElementTree as ET
  2.  
  3. ############ 解析方式一 ############
  4. """
  5. # 打开文件,读取XML内容
  6. str_xml = open('xo.xml', 'r').read()
  7.  
  8. # 将字符串解析成xml特殊对象,root代指xml文件的根节点
  9. root = ET.XML(str_xml)
  10. """
  11. ############ 解析方式二 ############
  12.  
  13. # 直接解析xml文件
  14. tree = ET.parse("xo.xml")
  15.  
  16. # 获取xml文件的根节点
  17. root = tree.getroot()
  18.  
  19. ### 操作
  20.  
  21. # 顶层标签
  22. print(root.tag)
  23.  
  24. # 遍历XML文档的第二层
  25. for child in root:
  26. # 第二层节点的标签名称和标签属性
  27. print(child.tag, child.attrib)
  28. # 遍历XML文档的第三层
  29. for i in child:
  30. # 第二层节点的标签名称和内容
  31. print(i.tag,i.text)

b、遍历XML中指定的节点

  1. from xml.etree import ElementTree as ET
  2.  
  3. ############ 解析方式一 ############
  4. """
  5. # 打开文件,读取XML内容
  6. str_xml = open('xo.xml', 'r').read()
  7.  
  8. # 将字符串解析成xml特殊对象,root代指xml文件的根节点
  9. root = ET.XML(str_xml)
  10. """
  11. ############ 解析方式二 ############
  12.  
  13. # 直接解析xml文件
  14. tree = ET.parse("xo.xml")
  15.  
  16. # 获取xml文件的根节点
  17. root = tree.getroot()
  18.  
  19. ### 操作
  20.  
  21. # 顶层标签
  22. print(root.tag)
  23.  
  24. # 遍历XML中所有的year节点
  25. for node in root.iter('year'):
  26. # 节点的标签名称和内容
  27. print(node.tag, node.text)

c、修改节点内容

由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。

  1. from xml.etree import ElementTree as ET
  2.  
  3. ############ 解析方式一 ############
  4.  
  5. # 打开文件,读取XML内容
  6. str_xml = open('xo.xml', 'r').read()
  7.  
  8. # 将字符串解析成xml特殊对象,root代指xml文件的根节点
  9. root = ET.XML(str_xml)
  10.  
  11. ############ 操作 ############
  12.  
  13. # 顶层标签
  14. print(root.tag)
  15.  
  16. # 循环所有的year节点
  17. for node in root.iter('year'):
  18. # 将year节点中的内容自增一
  19. new_year = int(node.text) + 1
  20. node.text = str(new_year)
  21.  
  22. # 设置属性
  23. node.set('name', 'alex')
  24. node.set('age', '')
  25. # 删除属性
  26. del node.attrib['name']
  27.  
  28. ############ 保存文件 ############
  29. tree = ET.ElementTree(root)
  30. tree.write("newnew.xml", encoding='utf-8')

解析字符串方式,删除,保存

  1. from xml.etree import ElementTree as ET
  2.  
  3. ############ 解析方式二 ############
  4.  
  5. # 直接解析xml文件
  6. tree = ET.parse("xo.xml")
  7.  
  8. # 获取xml文件的根节点
  9. root = tree.getroot()
  10.  
  11. ############ 操作 ############
  12.  
  13. # 顶层标签
  14. print(root.tag)
  15.  
  16. # 循环所有的year节点
  17. for node in root.iter('year'):
  18. # 将year节点中的内容自增一
  19. new_year = int(node.text) + 1
  20. node.text = str(new_year)
  21.  
  22. # 设置属性
  23. node.set('name', 'alex')
  24. node.set('age', '')
  25. # 删除属性
  26. del node.attrib['name']
  27.  
  28. ############ 保存文件 ############
  29. tree.write("newnew.xml", encoding='utf-8')

解析文件方式,删除,保存

3、创建XML文档

  1. from xml.etree import ElementTree as ET
  2.  
  3. # 创建根节点
  4. root = ET.Element("famliy")
  5.  
  6. # 创建节点大儿子
  7. son1 = ET.SubElement(root, "son", attrib={'name': '儿1'})
  8. # 创建小儿子
  9. son2 = ET.SubElement(root, "son", attrib={"name": "儿2"})
  10.  
  11. # 在大儿子中创建一个孙子
  12. grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'})
  13. grandson1.text = '孙子'
  14.  
  15. et = ET.ElementTree(root) #生成文档对象
  16. et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)

创建方式一

  1. from xml.etree import ElementTree as ET
  2.  
  3. # 创建根节点
  4. root = ET.Element("famliy")
  5.  
  6. # 创建节点大儿子
  7. son1 = ET.Element('son', {'name': '儿1'})
  8. # 创建小儿子
  9. son2 = ET.Element('son', {"name": '儿2'})
  10.  
  11. # 在大儿子中创建两个孙子
  12. grandson1 = ET.Element('grandson', {'name': '儿11'})
  13. grandson2 = ET.Element('grandson', {'name': '儿12'})
  14. son1.append(grandson1)
  15. son1.append(grandson2)
  16.  
  17. # 把儿子添加到根节点中
  18. root.append(son1)
  19. root.append(son1)
  20.  
  21. tree = ET.ElementTree(root)
  22. tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

创建方式二

  1. from xml.etree import ElementTree as ET
  2.  
  3. # 创建根节点
  4. root = ET.Element("famliy")
  5.  
  6. # 创建大儿子
  7. # son1 = ET.Element('son', {'name': '儿1'})
  8. son1 = root.makeelement('son', {'name': '儿1'})
  9. # 创建小儿子
  10. # son2 = ET.Element('son', {"name": '儿2'})
  11. son2 = root.makeelement('son', {"name": '儿2'})
  12.  
  13. # 在大儿子中创建两个孙子
  14. # grandson1 = ET.Element('grandson', {'name': '儿11'})
  15. grandson1 = son1.makeelement('grandson', {'name': '儿11'})
  16. # grandson2 = ET.Element('grandson', {'name': '儿12'})
  17. grandson2 = son1.makeelement('grandson', {'name': '儿12'})
  18.  
  19. son1.append(grandson1)
  20. son1.append(grandson2)
  21.  
  22. # 把儿子添加到根节点中
  23. root.append(son1)
  24. root.append(son1)
  25.  
  26. tree = ET.ElementTree(root)
  27. tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

创建方式三

注:

  1. shorrt_empty_element = False 没有内容不自闭合
  2. xml_declaration = True xml开头注释

由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:

  1. from xml.etree import ElementTree as ET
  2. from xml.dom import minidom
  3.  
  4. def prettify(elem):
  5. """将节点转换成字符串,并添加缩进。
  6. """
  7. rough_string = ET.tostring(elem, 'utf-8')
  8. reparsed = minidom.parseString(rough_string)
  9. return reparsed.toprettyxml(indent="\t")
  10.  
  11. # 创建根节点
  12. root = ET.Element("famliy")
  13.  
  14. # 创建大儿子
  15. # son1 = ET.Element('son', {'name': '儿1'})
  16. son1 = root.makeelement('son', {'name': '儿1'})
  17. # 创建小儿子
  18. # son2 = ET.Element('son', {"name": '儿2'})
  19. son2 = root.makeelement('son', {"name": '儿2'})
  20.  
  21. # 在大儿子中创建两个孙子
  22. # grandson1 = ET.Element('grandson', {'name': '儿11'})
  23. grandson1 = son1.makeelement('grandson', {'name': '儿11'})
  24. # grandson2 = ET.Element('grandson', {'name': '儿12'})
  25. grandson2 = son1.makeelement('grandson', {'name': '儿12'})
  26.  
  27. son1.append(grandson1)
  28. son1.append(grandson2)
  29.  
  30. # 把儿子添加到根节点中
  31. root.append(son1)
  32. root.append(son1)
  33.  
  34. raw_str = prettify(root)
  35.  
  36. f = open("xxxoo.xml",'w',encoding='utf-8')
  37. f.write(raw_str)
  38. f.close()

4、命名空间

详细介绍,猛击这里

  1. from xml.etree import ElementTree as ET
  2.  
  3. ET.register_namespace('com',"http://www.company.com") #some name
  4.  
  5. # build a tree structure
  6. root = ET.Element("{http://www.company.com}STUFF")
  7. body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": ""})
  8. body.text = "STUFF EVERYWHERE!"
  9.  
  10. # wrap it in an ElementTree instance, and save as XML
  11. tree = ET.ElementTree(root)
  12.  
  13. tree.write("page.xml",
  14. xml_declaration=True,
  15. encoding='utf-8',
  16. method="xml")

命名空间

八、configparser

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

  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

config文件格式

  读取时,文件内容均为字符串类型,不需要加""

  1. # 注释1
  2. ; 注释2
  3.  
  4. [section1] # 节点
  5. k1 = v1 # 值
  6. k2:v2 # 值
  7.  
  8. [section2] # 节点
  9. k1 = v1 # 值

1、获取所有节点

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config.read('xxxooo', encoding='utf-8')
  5. ret = config.sections()
  6. print(ret)

2、获取指定节点下所有的键值对

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config.read('xxxooo', encoding='utf-8')
  5. ret = config.items('section1')
  6. print(ret)

3、获取指定节点下所有的建

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config.read('xxxooo', encoding='utf-8')
  5. ret = config.options('section1')
  6. print(ret)

4、获取指定节点下指定key的值

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config.read('xxxooo', encoding='utf-8')
  5.  
  6. v = config.get('section1', 'k1')
  7. # v = config.getint('section1', 'k1')
  8. # v = config.getfloat('section1', 'k1')
  9. # v = config.getboolean('section1', 'k1')
  10.  
  11. print(v)

5、检查、删除、添加节点

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config.read('xxxooo', encoding='utf-8')
  5.  
  6. # 检查
  7. has_sec = config.has_section('section1')
  8. print(has_sec)
  9.  
  10. # 添加节点
  11. config.add_section("SEC_1")
  12. config.write(open('xxxooo', 'w'))
  13.  
  14. # 删除节点
  15. config.remove_section("SEC_1")
  16. config.write(open('xxxooo', 'w'))

6、检查、删除、设置指定组内的键值对

  1. import configparser
  2.  
  3. config = configparser.ConfigParser()
  4. config.read('xxxooo', encoding='utf-8')
  5.  
  6. # 检查
  7. has_opt = config.has_option('section1', 'k1')
  8. print(has_opt)
  9.  
  10. # 删除
  11. config.remove_option('section1', 'k1')
  12. config.write(open('xxxooo', 'w'))
  13.  
  14. # 设置
  15. config.set('section1', 'k10', "123")
  16. config.write(open('xxxooo', 'w'))

九、logging

用于便捷记录日志且线程安全的模块

1、单文件日志 (只记录到文件中,屏幕不显示信息)

  1. import logging
  2.  
  3. logging.basicConfig(filename='log.log',
  4. format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
  5. datefmt='%Y-%m-%d %H:%M:%S %p',
  6. level=10) # level=logging.DEBUG
  7.  
  8. logging.debug('debug')
  9. logging.info('info')
  10. logging.warning('warning')
  11. logging.error('error')
  12. logging.critical('critical')
  13. logging.log(10,'log')

日志等级:

  1. CRITICAL = 50
  2. FATAL = CRITICAL
  3. ERROR = 40
  4. WARNING = 30
  5. WARN = WARNING
  6. INFO = 20
  7. DEBUG = 10
  8. NOTSET = 0

注:只有【当前写等级】大于【日志等级】时,日志文件才被记录。

日志记录格式:

  1. format参数中可能用到的格式化串:
  2. %(name)s Logger的名字
  3. %(levelno)s 数字形式的日志级别
  4. %(levelname)s 文本形式的日志级别
  5. %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
  6. %(filename)s 调用日志输出函数的模块的文件名
  7. %(module)s 调用日志输出函数的模块名
  8. %(funcName)s 调用日志输出函数的函数名
  9. %(lineno)d 调用日志输出函数的语句所在的代码行
  10. %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
  11. %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
  12. %(asctime)s 字符串形式的当前时间。默认格式是 2003-07-08 16:49:45,896”。逗号后面的是毫秒
  13. %(thread)d 线程ID。可能没有
  14. %(threadName)s 线程名。可能没有
  15. %(process)d 进程ID。可能没有
  16. %(message)s用户输出的消息

format参数

2、多文件日志

对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。

  1. # 定义文件
  2. file_1_1 = logging.FileHandler('l1_1.log', 'a', encoding='utf-8')
  3. fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
  4. file_1_1.setFormatter(fmt)
  5.  
  6. file_1_2 = logging.FileHandler('l1_2.log', 'a', encoding='utf-8')
  7. fmt = logging.Formatter()
  8. file_1_2.setFormatter(fmt)
  9.  
  10. # 定义日志
  11. logger1 = logging.Logger('s1', level=logging.ERROR)
  12. logger1.addHandler(file_1_1)
  13. logger1.addHandler(file_1_2)
  14.  
  15. # 写日志
  16. logger1.critical('')

日志(一)

  1. # 定义文件
  2. file_2_1 = logging.FileHandler('l2_1.log', 'a')
  3. fmt = logging.Formatter()
  4. file_2_1.setFormatter(fmt)
  5.  
  6. # 定义日志
  7. logger2 = logging.Logger('s2', level=logging.INFO)
  8. logger2.addHandler(file_2_1)

日志(二)

如上述创建的两个日志对象

  • 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中

  • 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中

3、Logger对象

  模块级别的函数是logging.getLogger([name])(返回一个logger对象,如果没有指定名字将返回root logger)

  1. import logging
  2.  
  3. logger = logging.getLogger()
  4.  
  5. # 创建一个handler,用于写入日志文件
  6. fh = logging.FileHandler('test.log')
  7.  
  8. # 再创建一个handler,用于输出到控制台
  9. ch = logging.StreamHandler()
  10.  
  11. formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
  12.  
  13. fh.setFormatter(formatter)
  14. ch.setFormatter(formatter)
  15.  
  16. logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
  17. logger.addHandler(ch)
  18.  
  19. logger.debug('logger debug message')
  20. logger.info('logger info message')
  21. logger.warning('logger warning message')
  22. logger.error('logger error message')
  23. logger.critical('logger critical message')

logging库提供了多个组件:Logger、Handler、Filter、Formatter。

Logger对象提供应用程序可直接使用的接口,Handler发送日志到适当的目的地,Filter提供了过滤日志信息的方法,Formatter指定日志显示格式。

可以通过Logger.setLevel(lel)指定最低的日志级别,可用的日志级别有logging.DEBUG、logging.INFO、logging.WARNING、logging.ERROR、logging.CRITICAL。

Logger.debug()、Logger.info()、Logger.warning()、Logger.error()、Logger.critical()输出不同级别的日志,只有日志等级大于或等于设置的日志级别的日志才会被输出。

十、Random

  1. import random
  2.  
  3. print(random.random()) #(0,1)----float
  4.  
  5. print(random.randint(1,3)) #[1,3]
  6.  
  7. print(random.randrange(1,3)) #[1,3)
  8.  
  9. print(random.choice([1,'23',[4,5]])) #23
  10.  
  11. print(random.sample([1,'23',[4,5]],2)) #[[4, 5], '23']
  12.  
  13. print(random.uniform(1,3)) #1.927109612082716

  

【Python之路】第六篇--Python基础之模块的更多相关文章

  1. Python之路(第六篇)Python全局变量与局部变量、函数多层嵌套、函数递归

    一.局部变量与全局变量 1.在子程序中定义的变量称为局部变量,在程序的一开始定义的变量称为全局变量.全局变量作用域是整个程序,局部变量作用域是定义该变量的子程序. 全局变量没有任何缩进,在任何位置都可 ...

  2. 【Python之路】第九篇--Python基础之线程、进程和协程

    进程与线程之间的关系 线程是属于进程的,线程运行在进程空间内,同一进程所产生的线程共享同一内存空间,当进程退出时该进程所产生的线程都会被强制退出并清除.线程可与属于同一进程的其它线程共享进程所拥有的全 ...

  3. python之路第四篇(基础篇)

    一.冒泡算法实现: 方法一: li = [13,33,12,80,66,1] print li for m in range(4): num1 = li[m] num2 = li[m+1] if nu ...

  4. 【Python之路】第一篇--Linux基础命令

    pwd 命令 查看”当前工作目录“的完整路径 pwd -P # 显示出实际路径,而非使用连接(link)路径:pwd显示的是连接路径 .   表示当前目录 ..  表示上级目录 /  表示根目录 ls ...

  5. Python之路(第八篇)Python内置函数、zip()、max()、min()

    一.python内置函数 abs() 求绝对值 例子 print(abs(-2)) all() 把序列中每一个元素做布尔运算,如果全部都是true,就返回true, 但是如果是空字符串.空列表也返回t ...

  6. Python之路(第五篇) Python基本数据类型集合、格式化、函数

    一.变量总结 1.1 变量定义 记录某种状态或者数值,并用某个名称代表这个数值或状态. 1.2 变量在内存中的表现形式 Python 中一切皆为对象,数字是对象,列表是对象,函数也是对象,任何东西都是 ...

  7. 【Python之路】特别篇--Python正则表达式

    正则表达式的基础 正则表达式并不是Python的一部分. 正则表达式是用于处理字符串的强大工具,拥有自己独特的语法以及一个独立的处理引擎,效率上可能不如str自带的方法,但功能十分强大. 得益于这一点 ...

  8. 【Python之路】特别篇--Python面向对象(进阶篇)

    上一篇<Python 面向对象(初级篇)>文章介绍了面向对象基本知识: 面向对象是一种编程方式,此编程方式的实现是基于对 类 和 对象 的使用 类 是一个模板,模板中包装了多个“函数”供使 ...

  9. Python之路第五天,基础(6)-模块

    模块 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个 ...

  10. Python之路(第七篇)Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数

    一.作用域 return 可以返回任意值例子 def test1(): print("test1") def test(): print("test") ret ...

随机推荐

  1. S2SH整合

    Struts2.Spring.Hibernate三大框架在一个项目中的具体职责分配如下: 三大框架整合,导入各个框架和整合所需的包(本项目采用的是Struts2.3+spring3.0+hiberna ...

  2. 《.NET 编程结构》专题汇总

    <.NET 编程结构>专题汇总 前言     掌握一门技术,首要的是掌握其基础.     笔者从事.NET相关开发多年,也非常喜欢.NET,多年来也积累了很多相关的资料,在此将一些基础性的 ...

  3. Django入门实践(一)

    Django入门实践(一) Django编程思路+入门 认识Django有一个多月了,我觉得学习Django应该先理清它的编程思路.它是典型的MVC框架(在Django里也称MTV),我觉得Djang ...

  4. C#基础之方法和参数

    C#基础之方法和参数 接上一篇<C#基础之类型和成员基础以及常量.字段.属性> 实例方法.静态方法 C#中的方法分为两类,一种是属于对象(类型的实例)的,称之为实例方法,另一种是属于类型的 ...

  5. 命令版本git 分支篇-----不断更新中

    最近应用开发的过程中出现了一个小问题,顺便记录一下原因和方法--命令版本 开发中想看看过去某个版本的代码,我们先查看log git log commit f224a720b8192165a4e70f2 ...

  6. 用indexOf获取字符窜某个字符的所有位置

    indexOf方法可以传两个参数,第二个参数是传位置的参数,利用这点获取所有的位置.例如: var str = "hello world,welcome!"; var arr = ...

  7. [APUE]进程控制(中)

    一.wait和waitpid函数 当一个进程正常或异常终止时会向父进程发送SIGCHLD信号.对于这种信号系统默认会忽略.调用wait/waidpid的进程可能会: 阻塞(如果其子进程都还在运行); ...

  8. Dubbo源码学习--服务是如何发布的

    相关文章: Dubbo源码学习--服务是如何发布的 Dubbo源码学习--服务是如何引用的 ServiceBean ServiceBean 实现ApplicationListener接口监听Conte ...

  9. jQuery+HTML5声音提示

    WEB应用中,有时需要播放特定的声音,比如有新消息或者在线聊天消息声音提示,以前我们通过flash实现,今天我们将使用jQuery和HTML5结合示例来实现如何把声音提示带入WEB应用中. 在本例中, ...

  10. java转发和重定向

    1,请求重定向:客户端行为,response.sendRedirect(),从本质上讲等同于两次请求,前一次的请求对象不会保持,地址栏的URL地址会改变.2,请求转发:服务器行为,request.ge ...