1 #author F
2
3 #模块的定义:用来从逻辑上组织python代码(变量/函数/类/逻辑),本质就是实现一个功能(以py结尾的python文件 module.py, 使用模块->import module)
4 #包:本质就是一个文件夹(目录),必须带有一个__init.py__文件, 是从逻辑上组织模块的
5
6 name = "Aux Air conditioner"
7 def sayHello():
8 print("hello aoteman")
9
10
11 #导入方法
12 # 1.直接import,导入多个时用逗号分隔
13 # 2.from module import *,from module import logger,from module import logger as logger_module 和 import module 的区别;
14 # 3.from module import logger() 错误
15 # 如何导入一个包?
16
17
18 #import本质
19 # 导入模块的本质就是把python文件解释一遍
20 # 导入包的本质就是在解释包下面的 __init.py__文件
21 # import的前提是 找到他的目录 把包或者模块的目录加入到sys.path中sys.path.[append/insert](os.path.dirname(os.path.abspath(__file__)))
22 # import test (test = test.py all code)
23 # from test import name (name = 'code')
24 # 如何使用包下面的模块中的方法?
25 # import package
26 # package.test.test() ##init.py中使用import test (from . import test#从当前目录导入test ###.代表当前init.py的路径)
27
28
29 #导入优化
30 # from module import test #可以避免重复检索`
31
32
33 #模块的分类
34 # 1.标准库
35 # 2.开源模块(第三方模块)
36 # 3.自定义模块
37
38 #===============================标准库=======================================
39 # a.时间模块=>time与datetime
40 # 1)time.time():时间戳
41 # time.timezone:和UTC差的时间
42 # time.sleep():睡
43 # gmtime():把s转换成utc时间
44 # localtime():转换为本地时间(元组)
45 # time.mktime():元组形式转换为时间戳
46 # strftime("%Y-%m-%d %H:%M:%S", 元组的时间格式) 元组转格式化时间 strftime("格式",struct_time)
47 # strptime("2016-11-25 7:08:26","%Y-%m-%d %H:%M:%S") 格式化时间转元组 strptime(struct_time,"格式")
48 # asctime():转换元祖时间为str
49 # ctime():转换时间戳为str
50 # datetime.datetime类和date类
51 # datetime.datetime.now(): 获取当前时间
52 # datetime.datetime.now()+datetime.timedelta(+3): 获取时间,几天前几天后的时间 ; 默认是天
53 # datetime.datetime.now()+datetime.timedelta(-3): 获取时间,几天前几天后的时间
54 # datetime.datetime.now()+datetime.timedelta(hours=3): 获取时间,几天前几天后的时间
55 # datetime.datetime.now()+datetime.timedelta(minutes=-3): 获取时间,几天前几天后的时间
56 # 2)格式化的字符串
57 # 3)struct time元组的九个元素 time.localtime()
58 # 世界标准时间UTC 中国时间UTC+8
59
60 # b.random模块
61 # 1)random
62 # random.random() #0.26596789
63 # random.uniform(1,10) #9.894946
64 # random.randomint(1,3) #[1,3] 包括两端
65 # random.randrange(1,3) #[1,3) 顾前不顾后
66 # random.choice("hello") #随机取值 传参序列或字符串
67 # random.sample("sfetryeyety",3) #[t, e, y]
68 # items = [1,2,3,4,5,6,7]
69 # random.shuffle(items) #洗牌 [5,6,...] 乱序
70
71 # c.os模块:提供对操作系统调用的一些接口
72 # 1)os.getcwd()获取当前目录
73 # os.chdir("dirname") #changedir 改变工作目录 #os.chdir("c:\\Users") os.chdir(r"c:\Users\Data")
74 # os.curdir #返回当前目录
75 # os.pardir #返回上级目录
76 # os.mkdirs("dirname1/diename2") #递归创建目录
77 # os.removedirs("dirname1") #目录为空则删除并递归到上级目录 如若也为空 也删除
78 # os.mkdir("dirname") #生成单级目录 相当于shell 中 的mkdie dirname
79 # os.rmdir("dirname") #删除单级目录 若目录不为空则无法删除,报错 相当于shell中的rmdir dirname
80 # os.listdir("dirname") #列出指定目录下的所有文件和子目录 包括隐藏文件 并以列表方式打印
81 # os.remove() #删除一个文件
82 # os.rename("oldname","newname") #重命名文件/目录
83 # os.stat("path/filename") #获取其文件/目录信息
84 # os.sep #输出操作系统指定路径分隔符 win \\ linux \
85 # os.linesep #输出当前平台的 行终符 win \r\n linux \n os \r
86 # os.pathsep #输出用于分割文件路径的字符串
87 # os.name #输出字符串 只是当前使用平台 win>>nt linux>>posix
88 # os.system("bash command") #运行shell命令 直接显示
89 # os.environ #获取系统环境变量
90 # os.path.abspath(path) #返回path规范化的绝对路径
91 # os.path.split(path) #将path分割成路径和文件名 以二元组形式返回
92 # os.path.dirname(path) #返回path的目录 其实就是os.path.spilit的第一个目录
93 # os.path.basename(path) #返回path最后的文件名 如果path以\或者/结尾 则返回空值
94 # os.path.exists(path) #path存在 返回True 不存在则返回 False
95 # os.path.isabs(path) #path是绝对路径则返回True
96 # os.path.isfile(path) #path是一个存在的文件 返回True 不存在返回False
97 # os.path.isdir(path) #path是一个存在的目录 返回True
98 # os.path.join(path1[,path2,...]) #将多个路径组合后返回 第一个绝对路径之前的参数将被忽略
99 # os.path.getatime(path) #返回path所指向的目录或文件的最后存储时间
100 # os.path.getmtime(path) #返回path所指向的目录或文件的最后修改时间
101
102 # d.sys模块
103 # 1)sys.argv 命令行参数List,第一个元素是程序本身路径
104 # sys.exit(n) 退出程序,正常退出时exit(0)
105 # sys.version 获取python解释程序的版本信息
106 # sys.maxint 最大的int值
107 # sys.path 返回模块的搜索路径,初始化时使用python环境变量的值
108 # sys.platform 返回操作系统平台名称
109 # sys.stdout.write('please:')
110 # val = sys.stdin.readline()[:-1]
111
112 # e.shutil模块 : 用来copy文件 , 高级的文件文件夹压缩包处理模块
113 # 1)shutil.copyfileobj(fsrc,fdst[,length])
114 # shutil.copyfile(src,dst)
115 # shutil.copymode(src,dst) 仅拷贝权限 用户属组等都保持原来的 不变
116 # shutil.sopystat(src,dst) 拷贝权限的 所有信息 但不创建文件
117 # shutil.copy(src,dst) 拷贝文件和 权限
118 # shutil.copy(src,dst) 拷贝文件和状态信息
119 # shutil.ignore_patterns(*pattens)
120 # shutil.copytree(src,dst) 递归拷贝
121 # shutil.rmtree() 递归压缩
122 # shutil.move(src,dst) 递归移动文件
123 # shutil.make_archive(base_name,format,...) 创建压缩包并返回文件路径 路径最好不要包含自己压缩包所在的地方
124 # base_name:压缩包的文件名 也可以是压缩包的路径
125 # format:压缩包的种类 zip tar bztar gatar
126 # root_dir:要压缩的文件夹路径
127 # owner:用户 默认当前用户
128 # group:组, 默认当前组
129 # logger:用于记录日志, if 通常是logging.Logger对象
130 # zipfile模块:
131 # z = zipfile.Zipfile("manmanjieya.zip","w")
132 # z.write("a.log")
133 # print("休息一下")
134 # z.write("b.log")
135 # z.close()
136 # #解压
137 # z = zipfile.Zipfile("manmanjieya.zip","r")
138 # z.extractall()
139 # z.close()
140 #
141 # tarfile模块:
142 # t = tarfile.open("you.tar","r")
143 # t.add(".../a.zip",arcname="bbs.zip")
144 # t.add(".../b.zip",arcname="bbs2.zip")
145 # tar.close()
146 # #解压
147 # z = tarfile.open("manmanjieya.zip","r")
148 # z.extractall()
149 # z.close()
150
151 # f.json与packle模块 : 用于序列化的两个模块
152 # json:用于字符串与python数据类型之间的转换
153 # packle:用于python特有的类型和python的数据类型之间的转换
154 # json:dumps , dump , loads , load
155 # pickle:dumps, dump , loads, load
156 # shelve模块
157 # sf = shelve.open("filename")
158 # info = {"name":"ASD", "job":"workkk"}
159 # name = ["sss", "asdasda", "asd"]
160 # sf["name"] = name
161 # sf["info"] = info
162 # sf.close()
163 # file = shelve.open("filename")
164 # file.get("name")
165 # file.get("info")
166 # file.get("date")
167
168 # g.xml.etree.ElementTree as ET
169 # tree = ET.parse("xmltest.xml")
170 # root = tree.getroot()
171 # print(root) #返回内存地址
172 # print(root.tag) #根目录的标签名
173 # 遍历整个xml文档
174 # for child in root:
175 # print(child.tag, child.attrib)
176 # for i in child:
177 # print(i.tag, i.attrib, i.text)
178 #
179 # 只遍历year节点
180 # for node in root.iter('year'):
181 # print(node.tag, node.text)
182 # 修改
183 # for node in root.iter('year'):
184 # new_year = int(node.text)+1
185 # node.text = str(new_year)
186 # node.set("updated","yes")
187 # tree.write("xmltest.xml")
188 #
189 # 删除
190 # for country in root.findall("country"):
191 # rank = int(country.find('rank').text)
192 # if rank > 50:
193 # root.remove(country)
194 # 自己创建xml
195 # new_xml = ET.Element("namelist")
196 # name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
197 # age = ET.SubElement(name, "age", attrib={"checked": "no"})
198 # sex = ET.SubElement(name, "sex")
199 # sex.text = '33'
200 # name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
201 # age = ET.SubElement(name2, "age")
202 # age.text = '19'
203 #
204 # et = ET.ElementTree(new_xml) # 生成文档对象
205 # et.write("test.xml", encoding="utf-8", xml_declaration=True)
206 #
207 # ET.dump(new_xml) # 打印生成的格式
208
209 # h.pyYAML:处理ymal文档格式(配置文档) http://pyyaml.org/wiki/PyYAMLDocumentation
210
211 # i.ConfigParse模块:用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
212 #
213 # [DEFAULT]
214 # ServerAliveInterval = 45
215 # Compression = yes
216 # CompressionLevel = 9
217 # ForwardX11 = yes
218 #
219 # [bitbucket.org]
220 # User = hg
221 #
222 # [topsecret.server.com]
223 # Port = 50022
224 # ForwardX11 = no
225 #
226 # 如果想用python生成一个这样的文档怎么做呢?
227 #
228 # import configparser
229 #
230 # config = configparser.ConfigParser()
231 # config["DEFAULT"] = {'ServerAliveInterval': '45',
232 # 'Compression': 'yes',
233 # 'CompressionLevel': '9'}
234 #
235 # config['bitbucket.org'] = {}
236 # config['bitbucket.org']['User'] = 'hg'
237 # config['topsecret.server.com'] = {}
238 # topsecret = config['topsecret.server.com']
239 # topsecret['Host Port'] = '50022' # mutates the parser
240 # topsecret['ForwardX11'] = 'no' # same here
241 # config['DEFAULT']['ForwardX11'] = 'yes'
242 # with open('example.ini', 'w') as configfile:
243 # config.write(configfile)
244 # 配置文件的读取
245 # import configparser
246 # >>> config = configparser.ConfigParser()
247 # >>> config.sections()
248 # []
249 # >>> config.defaults()
250 # >>> config.read('example.ini')
251 # ['example.ini']
252 # >>> config.sections()
253 # ['bitbucket.org', 'topsecret.server.com']
254 # >>> 'bitbucket.org' in config
255 # True
256 # >>> 'bytebong.com' in config
257 # False
258 # >>> config['bitbucket.org']['User']
259 # 'hg'
260 # >>> config['DEFAULT']['Compression']
261 # 'yes'
262 # >>> topsecret = config['topsecret.server.com']
263 # >>> topsecret['ForwardX11']
264 # 'no'
265 # >>> topsecret['Port']
266 # '50022'
267 # >>> for key in config['bitbucket.org']: print(key)
268 # user
269 # compressionlevel
270 # serveraliveinterval
271 # compression
272 # forwardx11
273 # >>> config['bitbucket.org']['ForwardX11']
274 # 'yes'
275 #
276 # configparser增删改查语法
277 #
278 # [section1]
279 # k1 = v1
280 # k2: v2
281 #
282 # [section2]
283 # k1 = v1
284 #
285 # import ConfigParser
286 #
287 # config = ConfigParser.ConfigParser()
288 # config.read('i.cfg')
289 # ########## 读 ##########
290 # secs = config.sections()
291 # print secs
292 # options = config.options('group2')
293 # print options
294 #
295 # item_list = config.items('group2')
296 # print item_list
297 #
298 # val = config.get('group1','key')
299 # val = config.getint('group1','key')
300 #
301 # ########## 改写 ##########
302 # sec = config.remove_section('group1')
303 # config.write(open('i.cfg', "w"))
304 #
305 # sec = config.has_section('wupeiqi')
306 # sec = config.add_section('wupeiqi')
307 # config.write(open('i.cfg', "w"))
308 #
309 #
310 # config.set('group2','k1',11111)
311 # config.write(open('i.cfg', "w"))
312 #
313 # config.remove_option('group2','age')
314 # config.write(open('i.cfg', "w"))
315
316 # j.hashlib模块:用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5算法
317 # import hashlib
318 #
319 # m = hashlib.md5()
320 # m.update(b"Hello")
321 # m.update(b"It's me")
322 # print(m.digest())
323 # m.update(b"It's been a long time since last time we ...")
324 #
325 # print(m.digest()) # 2进制格式hash
326 # print(len(m.hexdigest())) # 16进制格式hash
327 # '''
328 # def digest(self, *args, **kwargs): # real signature unknown
329 # """ Return the digest value as a string of binary data. """
330 # pass
331 #
332 # def hexdigest(self, *args, **kwargs): # real signature unknown
333 # """ Return the digest value as a string of hexadecimal digits. """
334 # pass
335 #
336 # '''
337 # import hashlib
338 #
339 # # ######## md5 ########
340 #
341 # hash = hashlib.md5()
342 # hash.update('admin')
343 # print(hash.hexdigest())
344 #
345 # # ######## sha1 ########
346 #
347 # hash = hashlib.sha1()
348 # hash.update('admin')
349 # print(hash.hexdigest())
350 #
351 # # ######## sha256 ########
352 #
353 # hash = hashlib.sha256()
354 # hash.update('admin')
355 # print(hash.hexdigest())
356 #
357 # # ######## sha384 ########
358 #
359 # hash = hashlib.sha384()
360 # hash.update('admin')
361 # print(hash.hexdigest())
362 #
363 # # ######## sha512 ########
364 #
365 # hash = hashlib.sha512()
366 # hash.update('admin')
367 # print(hash.hexdigest())
368 #
369 # 还不够吊?python还有一个hmac模块,它内部对我们创建key和内容再进行处理然后再加密散列消息鉴别码,简称HMAC,是一种基于消息鉴别码MAC(Message Authentication Code)的鉴别机制。使用HMAC时, 消息通讯的双方,通过验证消息中加入的鉴别密钥K来鉴别消息的真伪;
370 # 一般用于网络通信中消息加密,前提是双方先要约定好key, 就像接头暗号一样,然后消息发送把用key把消息加密,接收方用key + 消息明文再加密,拿加密后的值跟发送者的相对比是否相等,这样就能验证消息的真实性,及发送者的合法性了。
371
372 # import hmac
373 # h = hmac.new('天王盖地虎'.encode(encoding="utf-8"), '宝塔镇河妖'.encode(encoding="utf-8"))
374 # print(h.hexdigest())
375 # https: // www.tbs - certificates.co.uk / FAQ / en / sha256.html
376
377 # k.re模块:常用正则表达式符号
378 # '.'
379 # 默认匹配除\n之外的任意一个字符,若指定flagDOTALL, 则匹配任意字符,包括换行
380 # '^'
381 # 匹配字符开头,若指定flags
382 # MULTILINE, 这种也可以匹配上(r"^a", "\nabc\neee", flags=re.MULTILINE)
383 # '$'
384 # 匹配字符结尾(整个字符串以xx结尾),或e.search("foo$", "bfoo\nsdfsf", flags=re.MULTILINE).group()
385 # 也可以
386 # '*'
387 # 匹配 * 号前的字符0次或多次,re.findall("ab*", "cabb3abcbbac")结果为['abb', 'ab', 'a']
388 # '+'
389 # 匹配前一个字符1次或多次,re.findall("ab+", "ab+cd+abb+bba")
390 # 结果['ab', 'abb']
391 # '?'
392 # 匹配前一个字符1次或0次
393 # '{m}'
394 # 匹配前一个字符m次
395 # '{n,m}'
396 # 匹配前一个字符n到m次,re.findall("ab{1,3}", "abb abc abbcbbb")
397 # 结果
398 # ['abb', 'ab', 'abb']
399 # '|'
400 # 匹配 | 左或 | 右的字符,re.search("abc|ABC", "ABCBabcCD").group()结果'ABC'
401 # '(...)'
402 # 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group()结果abcabca456c
403 # '\A'
404 # 只从字符开头匹配,re.search("\Aabc", "alexabc")是匹配不到的
405 # '\Z'
406 # 匹配字符结尾,同$
407 # '\d'
408 # 匹配数字0 - 9
409 # '\D'
410 # 匹配非数字
411 # '\w'
412 # 匹配[A-Za-z0-9]
413 # '\W'
414 # 匹配非[A-Za-z0-9]
415 # '\s'
416 # 匹配空白字符、\t、\n、\r, re.search("\s+", "ab\tc1\n3").group()结果'\t'
417 # [a-z]
418 # 匹配[a-z]之间的一个字符
419
420 # '(?P<name>...)'
421 # 分组匹配
422 # re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})", "371481199306143242").groupdict("city")
423 # 结果
424 # {'province': '3714', 'city': '81', 'birthday': '1993'}
425 #
426 # 最常用的匹配语法
427 # re.match 从头开始匹配
428 # re.search 匹配包含 (用的最多)
429 # re.findall 把所有匹配到的字符放到以列表中的元素返回
430 # re.split 以匹配到的字符当做列表分隔符
431 # re.sub 匹配字符并替换
432 #
433 # 反斜杠的困扰:与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":前两个和后两个分别用于在编程语言里转义成反斜杠,转换成两个反斜杠后再在正则表达式里转义成一个反斜杠。Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。同样,匹配一个数字的"\\d"可以写成r"\d"。有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。
434 #
435 # re.I(re.IGNORECASE): 忽略大小写(括号内是完整写法,下同)
436 # M(MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
437 # S(DOTALL): 点任意匹配模式,改变'.'的行为