1. 程式人生 > >老男孩14期自動化運維day5隨筆和作業

老男孩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"))