老男孩14期自动化运维day5随笔和作业

常用模块学习
1.什么是模块
(1)模块的定义
模块:用来从逻辑上组织python代码(变量,函数,类,逻辑:实现一个功能),本职就是.py结尾的python文件
(2) 导入模块方法:
import module_name
import module1_name,module2_name
from package import module_name(module_name 在package包下)
from module_1 import * (不建议使用,因为导入的是module_1所有的函数拿到当前位置编译一边,容易产生在模块内的函数名与本python文件内的函数名重复,原来模块内的函数会被覆盖)
from module_2 import m1,m2,m3(m1,m2,m3为方法或函数)
from module import logger as logger_yang
(3)import本质(路径搜索和搜索路径)
导入模块的本质就是把python文件解释一边(import test test=‘test.py all code’ )
import module_name —>module_name.py---->module_name.py的路径---->sys.path
(4)导入包:
本质:就是执行该包下的__init__.py文件

2.re模块
正则表达式模块

#!/usr/bin/env python
# coding:utf-8
# Author:Yang

import re

print(re.match(".+","asde")) # 指定除\n任意字符  match 方法只从字符串开头往后匹配
print(re.search("^a","adade")) # 匹配字符开头
print(re.search("de$","adade")) # 匹配字符结尾
print(re.search("R[a-z]+a","Chen321Ronghua123a"))
print(re.search("ad*","sadea")) # *前字符零次或多次
print(re.findall("ad*","sadea"))
print(re.findall("a*","asdeda"))
print(re.match("a+","sdad"))  # match 从开头匹配
print(re.search("a?","asdwdasdw").group()) # group() 得到结果
print(re.search("aaa?","aaaalex"))  # 符号前 0个或1个
print(re.search("[0-9]{3}","dada1dq2aa4ada4"))  # {}匹配几次
print(re.search("[0-9]{1,3}","dada1dq2aa4ada4"))  # 匹配1到3次 只匹配1
print(re.findall("[0-9]{1,3}","dada1dq2aa4ada4"))  # 匹配1到3次 都要匹配  findall没有group方法
print(re.search("abc|ABC","ABCBabcCD")) # |左或|右
# \A 开头 同^
# \Z 结尾 同$
# \d 数字
# \D 非数字
# \w 匹配[A-Za-z0-9]
# 匹配非[A-Za-z0-9]
# \s 匹配空白字符(\t,\n,\s)


# 分组匹配
print(re.search("(?P<id>[0-9]+)","abcd1234daf034").groupdict())
print(re.search("(?P<id>[0-9]+)(?P<name>[a-zA-Z]+)","abcd1234daf034").groupdict())

# split
print(re.split("[0-9]+","abc12de3f45GH")) # 分割

# sub
print(re.sub("[0-9]+","|","abc12de3f45GH")) # 替换
print(re.sub("[0-9]+","|","abc12de3f45GH",count=2)) # 替换

# 匹配\
print(re.search("\\\\","abc12de\\3f45GH"))
print(re.search(r"\\","abc12de\\3f45GH")) # 其实结果是一个\

3.time模块

#!/usr/bin/env python
# coding:utf-8
# Author:Yang

import time
print(time.time()) # 时间戳
print(help(time.gmtime()))

x=time.localtime(123411)
print(x)
print(time.strftime("%Y-%m-%d"))
print(x.tm_hour)
print(time.asctime())
print(time.ctime(1231231)) # 时间戳转格式化

4.random模块
random为随机数模块,注意random()的值域为(0,1)

#!/usr/bin/env python
# coding:utf-8
# Author:Yang
import random
print(random.random()) # (0,1) 随机数
print(random.randint(1,7)) # 1到7 包含7
print(random.randrange(10)) # 取不到10 顾头不顾尾 0到9
print(random.choice('asda')) # 从字符串随机找
print(random.sample('asdac',2)) # 从前二随机取两个
print(random.uniform(1,3)) # 可以定义区间


# random实现简易验证码

checkcode = ''

for i in range(4):
    current = random.randrange(0,4)
    # 字母
    if current == i:
        tmp=chr(random.randint(65,90)) #65->A 90->Z
    else:
    #数字
        tmp=random.randint(0,9)
    checkcode +=str(tmp)

print(checkcode)


5.xml模块
xml格式文件的遍历解析

#!/usr/bin/env python
# coding:utf-8
# Author:Yang

import xml.etree.ElementTree as ET

tree=ET.parse("test.xml")
root=tree.getroot()
print(root.tag)

for child in root:
    print(child.tag,child.text)
    for i in child:
        print(i.tag,i.text)

for node in root.iter('from'):
    print(node.tag,node.text)

6.shutil模块
复制、压缩、解压文件模块

import shutil

f1 = open("本节笔记",encoding="utf-8")

f2 = open("笔记2","w",encoding="utf-8")
shutil.copyfileobj(f1,f2)

shutil.copyfile("笔记2","笔记3")
shutil.copystat("本节笔记","笔记3")

shutil.copytree("test4","new_test4")
shutil.rmtree("new_test4")

shutil.make_archive("shutil_archive_test", "zip","E:\PycharmProjects\pyday1\day5")

7.shelve模块
持久化存储模块

import shelve
import datetime
d = shelve.open('shelve_test')  # 打开一个文件
print(d.get("name"))
print(d.get("info"))
print(d.get("date"))

# info =  {'age':22,"job":'it'}
#
# name = ["alex", "rain", "test"]
# d["name"] = name  # 持久化列表
# d["info"] = info  # 持久dict
# d['date'] = datetime.datetime.now()
# d.close()

8.hashlib模块
加密模块

#!/usr/bin/env python
# coding:utf-8
# Author:Yang

import hashlib,hmac
m = hashlib.md5()
m.update(b"hello")
print(m.hexdigest()) # 16进制

h=hmac.new(b"123","样".encode(encoding="utf-8"))
print(h.digest())
print(h.hexdigest()) # 双层加密

9.configparaser模块
生成类似MySQL中的配置文件my.ini格式的文件
(1)configparaser生成

import configparser #ConfigParser

config = configparser.ConfigParser()

config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
config['topsecret.server.com']
config['topsecret.server.com']['Host Port'] = '50022'  # mutates the parser
config['topsecret.server.com']['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'


with open('example.ini', 'w') as configfile:
    config.write(configfile)

(2)configparaser读取

import configparser

conf = configparser.ConfigParser()
conf.read("example.ini")

print(conf.defaults())
print(conf['bitbucket.org']['user'])
#print(conf.sections())
sec = conf.remove_section('bitbucket.org')
conf.write(open('example.ini', "w"))

猜你喜欢

转载自blog.csdn.net/qq_33060225/article/details/83823709
今日推荐