python的主要应用领域及常用的函数模块_python之常用模块篇5
一、日志模塊,logging模塊
1)logging模塊簡單使用,屏幕輸出。默認級別30
import logging
logging.debug('debug...') # 10logging.info('info....') #20logging.warning('可能著火...') #30logging.error('著火啦快跑') # 40logging.critical('火越燒越大') #50
View Code
2)控制日志輸出到文件,但屏幕顯示信息會消失。注意,存入文件時是以gbk,所以打開時,也要指定gbk格式
import logging
# 控制日志輸出
logging.basicConfig(
filename='access.log', # 記錄在當前目錄,生成文件
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
# 時間 日志的名,如debug,error 級別 模塊 # 接收的信息
datefmt='%Y-%m-%d %H:%M:%S %p', # 時間
level=20,
)
logging.debug('debug...') # 10logging.info('info....') #20logging.warning('可能著火...') #30logging.error('著火啦快跑') # 40logging.critical('火越燒越大') #50
View Code
3)日志模塊調用原理
import logging
#logger對象:用來產生日志
logger1=logging.getLogger('銀行業務相關') # 日志名是用告訴我們所記錄的日志到底是屬于哪一類業務相關的信息
#filter對象:過濾日志
#handler對象:控制日志的去向: 文件 或 終端
fh1=logging.FileHandler('a1.log',encoding='utf-8')
fh2=logging.FileHandler('a2.log',encoding='utf-8')
ch=logging.StreamHandler() #代表的就是終端
# 建立logger對象與handler對象的綁定關系
logger1.addHandler(fh1)
logger1.addHandler(fh2)
logger1.addHandler(ch)
#formmatter對象:定制日志的格式
formatter1=logging.Formatter(
fmt='%(asctime)s - %(name)s - %(levelname)s - %(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p')
formatter2=logging.Formatter(
fmt='%(asctime)s ===> %(message)s',
)
# 為handler對象綁定日志格式
fh1.setFormatter(formatter1)
fh2.setFormatter(formatter2)
ch.setFormatter(formatter2)
#設置日志級別:兩層關卡,第一次是logger,第二層是handler,只有兩層都放行,最終日志才會打印
# logger1.setLevel(50)
# fh1.setLevel(10)
# fh2.setLevel(10)
# ch.setLevel(10)
logger1.setLevel(10)
fh1.setLevel(10)
fh2.setLevel(10)
ch.setLevel(10)
# 調用logger對象產生日志
logger1.debug('這是一條debug日志')
View Code
4)引用字典加載日志模塊配置
日志配置文件,setting_log.py
import logging
# 定義日志文件的保存路徑
logfile_path=r'D:\oldboyedu\manth-02\day-02\a1.log'# 定義日志格式
standard_format= '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'\'[%(levelname)s][%(message)s]'#其中name為getlogger指定的名字
simple_format= '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'# log配置字典
LOGGING_DIC={'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': standard_format
},'simple': {'format': simple_format
},
},'filters': {},'handlers': {
#打印到終端的日志'console': {'level': 'DEBUG','class': 'logging.StreamHandler', # 打印到終端'formatter': 'simple'},
#打印到文件的日志,'default': {'level': 'DEBUG','class': 'logging.FileHandler', # 保存到文件 # logging.handlers.RotatingFileHandler'formatter': 'standard','filename': logfile_path, # 日志文件'encoding': 'utf-8', # 日志文件的編碼,再也不用擔心中文log亂碼了
},
},'loggers': {
#logging.getLogger(__name__)拿到的logger配置'logger1': {'handlers': ['default', 'console'],'level': 'DEBUG','propagate': False,
},
},
}
setting_log
升級修改的配置文件,增加日志輪轉的功能
'default': {'level': 'DEBUG',
#'class': 'logging.FileHandler', # 保存到文件 # logging.handlers.RotatingFileHandler'class': 'logging.handlers.RotatingFileHandler','formatter': 'standard','filename': logfile_path, # 日志文件'maxBytes': 1024*1024*5, # 日志文件大小 5M'backupCount': 5,'encoding': 'utf-8', # 日志文件的編碼,再也不用擔心中文log亂碼了
},
View Code
功能調用日志模塊配置文件
import logging.configfromsetting_log import LOGGING_DIC # 導入日志的配置文件
logging.config.dictConfig(LOGGING_DIC)
logging1= logging.getLogger('logger1')
logging1.debug('調試日志')
View Code
5)升級版,新增配置日志文件,如boss的日志
import logging
# 定義日志文件的保存路徑
logfile_path=r'D:\oldboyedu\manth-02\day-02\a1.log'boss_logfile_path=r'D:\oldboyedu\manth-02\day-02\a2.log'# 定義日志格式
standard_format= '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'\'[%(levelname)s][%(message)s]'#其中name為getlogger指定的名字
simple_format= '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'id_simple_format= '[%(asctime)s] %(message)s'# 給boss的日志,簡單明了的日志
# log配置字典
LOGGING_DIC={'version': 1,'disable_existing_loggers': False,'formatters': {'standard': {'format': standard_format
},'simple': {'format': simple_format
},'id_simple': {'format': id_simple_format
}
},'filters': {},'handlers': {
#打印到終端的日志'console': {'level': 'DEBUG','class': 'logging.StreamHandler', # 打印到終端'formatter': 'simple'},
#打印到文件的日志,'default': {'level': 'DEBUG','class': 'logging.FileHandler', # 保存到文件 # logging.handlers.RotatingFileHandler'formatter': 'standard','filename': logfile_path, # 日志文件'encoding': 'utf-8', # 日志文件的編碼,再也不用擔心中文log亂碼了
},
# 打印給boss的日志'boss': {'level': 'ERROR','class': 'logging.FileHandler', # 保存到文件 # logging.handlers.RotatingFileHandler'formatter': 'id_simple','filename': boss_logfile_path, # 日志文件'encoding': 'utf-8', # 日志文件的編碼,再也不用擔心中文log亂碼了
},
},'loggers': {
#logging.getLogger(__name__)拿到的logger配置'logger1': {'handlers': ['default', 'console','boss'],'level': 'DEBUG','propagate': False,
},
},
}
setting_log2
6)函數調用配置文件輸出日志
def get_logger(logger_name):
# 獲取輸入日志的信息
logging.config.dictConfig(settings.LOGGING_DIC) # 導入上面定義的settings配置
logger=logging.getLogger(logger_name)returnlogger
logger=get_logger('logger1')
def register():
logger.info('用戶%s注冊成功' %user)
def info():
logger.info('用戶%s登錄成功' %user)
View Code
7)可實現任意log對象的配置,字典的key為空即可
'loggers': {
#logging.getLogger(__name__)拿到的logger配置'': {'handlers': ['default', 'console'],'level': 'DEBUG','propagate': False,
},
},
任意log對象配置
8)擴展,log的日志格式
可在logging.basicConfig()函數中通過具體參數來更改logging模塊默認行為,可用參數有
filename:用指定的文件名創建FiledHandler(后邊會具體講解handler的概念),這樣日志會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值為“a”還可指定為“w”。
format:指定handler使用的日志顯示格式。
datefmt:指定日期時間格式。
level:設置rootlogger(后邊會講解具體概念)的日志級別
stream:用指定的stream創建StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者文件,默認為sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。
#格式%(name)s:Logger的名字,并非用戶名,詳細查看%(levelno)s:數字形式的日志級別%(levelname)s:文本形式的日志級別%(pathname)s:調用日志輸出函數的模塊的完整路徑名,可能沒有%(filename)s:調用日志輸出函數的模塊的文件名%(module)s:調用日志輸出函數的模塊名%(funcName)s:調用日志輸出函數的函數名%(lineno)d:調用日志輸出函數的語句所在的代碼行%(created)f:當前時間,用UNIX標準的表示時間的浮 點數表示%(relativeCreated)d:輸出日志信息時的,自Logger創建以 來的毫秒數%(asctime)s:字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號后面的是毫秒%(thread)d:線程ID。可能沒有%(threadName)s:線程名。可能沒有%(process)d:進程ID。可能沒有%(message)s:用戶輸出的消息
日志格式擴展
二、跨平臺序列化存儲數據。json和pickle
1)序列化的概念,意義
01什么是序列化
序列化:把內存中的數據轉成一種中間格式(json/pickle),然后存放到硬盤中,永久保存
反序列化:從文件中讀出(json/pickle)格式,然后返解成python的數據類型02為什么要序列化1、數據結構持久化2、跨平臺數據交互03如何進行序列化,反序列化
json:
缺點:
只能支持部分python的數據類型
優點:
所有的語言都支持json格式
應用:
如果需要考慮跨平臺性,則需要用json格式
pickle
缺點:
只有python支持pickle格式
優點:
pickle能夠支持所有的python數據類型
應用:
如果不需要考慮跨平臺性,則可以用pickle格式
View Code
2)json支持轉換python格式的類型
3)json序列化模塊的使用
import json
# dic={'name':'egon','age':18,'is_beautiful':True}
# #序列化
# res=json.dumps(dic) # 強調,json格式不識別單引號
# # print(res,type(res))
# with open('user.json','w',encoding='utf-8') asf:
# f.write(res)
# 反序列化
# with open('user.json','r',encoding='utf-8') asf:
# res=f.read()
# dic=json.loads(res)
# print(dic['name'])
# 強調,json格式不識別單引號
# with open('user1.json','r',encoding='utf-8') asf:
# res=f.read()
#
# dic=json.loads(res)
# print(dic['x'])
# #序列化
# dic={'name':'egon','age':18,'is_beautiful':True}
#
# with open('user2.json','w',encoding='utf-8') asf:
# json.dump(dic,f)
# 反序列化
with open('user.json','r',encoding='utf-8') asf:
dic=json.load(f)
print(dic['name'])
json的使用
4)pickle用法和json一模一樣
import json
import pickle
# 序列化
# pickle可以序列化任意python的數據類型
# print(json.dumps({1,2,3}))
# print(pickle.dumps({1,2,3}))
# dic={'name':'egon','age':18,'is_beautiful':True}
#
# res=pickle.dumps(dic)
# with open('user3.pkl','wb') asf:
# f.write(res)
# 反序列化
# with open('user3.pkl','rb') asf:
# res=f.read()
#
# dic=pickle.loads(res)
# print(dic['name'])
#簡單寫法
# # 序列化
# dic={'name':'egon','age':18,'is_beautiful':True}
# with open('user4.pkl','wb') asf:
# pickle.dump(dic,f)
# 反序列化
with open('user4.pkl','rb') asf:
dic=pickle.load(f)
print(dic['name'])
pkickle的使用
三、hash加密模塊
1)hash加密算法的用途
1、只要校驗的文本內容一樣,那么得到的hash值是相同===>校驗文件的完整性2、只要使用hash算法固定,無論校驗的內容有多大,得到的hash值長度都是固定的(與上一條合到一起用)3、hash不可以逆,即無法通過hash值反解出明文====》將明文轉成密文進行傳輸
View Code
2)hash的各種用法
import hashlib
# m=hashlib.md5() # 建造了一個hash工廠
# m.update(b'hello') # update接收的數據類型都必須是bytes類型
# m.update(b'world') # update接收的數據類型都必須是bytes類型
# m.update(b'egon') # update接收的數據類型都必須是bytes類型
# #b'helloworldegon'# print(m.hexdigest())
# m1=hashlib.md5() # 建造了一個hash工廠
# m1.update(b'hellowo') # update接收的數據類型都必須是bytes類型
# m1.update(b'rldegon') # update接收的數據類型都必須是bytes類型
# #b'helloworldegon'# print(m1.hexdigest())
# m2=hashlib.md5() # 建造了一個hash工廠
# m2.update(b'hellowo') # update接收的數據類型都必須是bytes類型
# m2.update(b'rldegon') # update接收的數據類型都必須是bytes類型
# m2.update(b'rldegon') # update接收的數據類型都必須是bytes類型
# print(m2.hexdigest())
#用途,驗證文件
# import hashlib
# m=hashlib.md5()
# with open('1.flv','rb') asf:
# #for line inf:
# # m.update(line)
# m.update(f.read())
# print(m.hexdigest())
# 升級加密,密碼寫在中間
# import hashlib
# password='alex3714'# m=hashlib.md5()
# m.update('天王蓋地虎'.encode('utf-8'))
# m.update(password.encode('utf-8'))
# m.update('小雞燉蘑菇'.encode('utf-8'))
# pwd_md5=m.hexdigest()
# print(pwd_md5)
# 查看hash的各個加密方法的難易度
# import hashlib
# m0=hashlib.md5()
# m0.update('hello'.encode('utf-8'))
# print(m0.hexdigest())
#
# m1=hashlib.sha256()
# m1.update('hello'.encode('utf-8'))
# print(m1.hexdigest())
#
# m2=hashlib.sha512()
# m2.update('hello'.encode('utf-8'))
# print(m2.hexdigest())
# 了解
import hmac
m=hmac.new('天王蓋地虎'.encode('utf-8'))
m.update(b'hello')
m.update(b'world')
print(m.hexdigest())
View Code
3)模擬撞庫
import hashlib
passwds=['alex3714','alex1313','alex94139413','alex123456','123456alex','a123lex',
]
def make_passwd_dic(passwds):
dic={}for passwd inpasswds:
m=hashlib.md5()
m.update(passwd.encode('utf-8'))
dic[passwd]=m.hexdigest()returndic
def break_code(cryptograph,passwd_dic):for k,v inpasswd_dic.items():if v ==cryptograph:
print('密碼是===>\033[46m%s\033[0m' %k)
cryptograph='aee949757a2e698417463d47acac93df'break_code(cryptograph,make_passwd_dic(passwds))
View Code
四、re正則模塊
1)基本正則練習
# =================================匹配模式=================================#一對一的匹配
#'hello'.replace(old,new)
#'hello'.find('pattern')
#正則匹配
import re
#\w與\W
print(re.findall('\w','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
print(re.findall('\W','hello egon 123')) #[' ', ' ']
#\s與\S
print(re.findall('\s','hello egon 123')) #[' ', ' ', ' ', ' ']
print(re.findall('\S','hello egon 123')) #['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
#\n \t都是空,都可以被\s匹配
print(re.findall('\s','hello \n egon \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']
#\n與\t
print(re.findall(r'\n','hello egon \n123')) #['\n']
print(re.findall(r'\t','hello egon\t123')) #['\n']
#\d與\D
print(re.findall('\d','hello egon 123')) #['1', '2', '3']
print(re.findall('\D','hello egon 123')) #['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
#\A與\Z
print(re.findall('\Ahe','hello egon 123')) #['he'],\A==>^print(re.findall('123\Z','hello egon 123')) #['he'],\Z==>$
#^與$
print(re.findall('^h','hello egon 123')) #['h']
print(re.findall('3$','hello egon 123')) #['3']
# 重復匹配:| . | * | ? | .* | .*? | + | {n,m} |#.
print(re.findall('a.b','a1b')) #['a1b']
print(re.findall('a.b','a1b a*b a b aaab')) #['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b','a\nb')) #[]
print(re.findall('a.b','a\nb',re.S)) #['a\nb']
print(re.findall('a.b','a\nb',re.DOTALL)) #['a\nb']同上一條意思一樣
#*print(re.findall('ab*','bbbbbbb')) #[]
print(re.findall('ab*','a')) #['a']
print(re.findall('ab*','abbbb')) #['abbbb']
#?print(re.findall('ab?','a')) #['a']
print(re.findall('ab?','abbb')) #['ab']
#匹配所有包含小數在內的數字
print(re.findall('\d+\.?\d*',"asdfasdf123as1.13dfa12adsf1asdf3")) #['123', '1.13', '12', '1', '3']
#.*默認為貪婪匹配
print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
#.*?為非貪婪匹配:推薦使用
print(re.findall('a.*?b','a1b22222222b')) #['a1b']
#+print(re.findall('ab+','a')) #[]
print(re.findall('ab+','abbb')) #['abbb']
#{n,m}
print(re.findall('ab{2}','abbb')) #['abb']
print(re.findall('ab{2,4}','abbb')) #['abb']
print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+'print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*'#[]
print(re.findall('a[1*-]b','a1b a*b a-b')) #[]內的都為普通字符了,且如果-沒有被轉意的話,應該放到[]的開頭或結尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]內的^代表的意思是取反,所以結果為['a=b']
print(re.findall('a[0-9]b','a1b a*b a-b a=b')) #[]內的^代表的意思是取反,所以結果為['a=b']
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) #[]內的^代表的意思是取反,所以結果為['a=b']
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) #[]內的^代表的意思是取反,所以結果為['a=b']
#\# print(re.findall('a\\c','a\c')) #對于正則來說a\\c確實可以匹配到a\c,但是在python解釋器讀取a\\c時,會發生轉義,然后交給re去執行,所以拋出異常
print(re.findall(r'a\\c','a\c')) #r代表告訴解釋器使用rawstring,即原生字符串,把我們正則內的所有符號都當普通字符處理,不要轉義
print(re.findall('a\\\\c','a\c')) #同上面的意思一樣,和上面的結果一樣都是['a\\c']
#():分組
print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的結果不是匹配的全部內容,而是組內的內容,?:可以讓結果為匹配的全部內容
print(re.findall('href="(.*?)"','點擊'))#['http://www.baidu.com']
print(re.findall('href="(?:.*?)"','點擊'))#['href="http://www.baidu.com"']
#|print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
View Code
2)re提供的方法
# ===========================re模塊提供的方法介紹===========================import re
#1print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有滿足匹配條件的結果,放在列表里
#2print(re.search('e','alex make love').group()) #e,只到找到第一個匹配然后返回一個包含匹配信息的對象,該對象可以通過調用group()方法得到匹配的字符串,如果字符串沒有匹配,則返回None。
#3print(re.match('e','alex make love')) #None,同search,不過在字符串開始處進行匹配,完全可以用search+^代替match
#4print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再對''和'bcd'分別按'b'分割
#5print('===>',re.sub('a','A','alex make love')) #===>Alex mAke love,不指定n,默認替換所有
print('===>',re.sub('a','A','alex make love',1)) #===>Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===>Alex mAke love
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===>love make alex
print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),結果帶有總共替換的個數
#6obj=re.compile('\d{2}')
print(obj.search('abc123eeee').group()) #12print(obj.findall('abc123eeee')) #['12'],重用了obj
View Code
3)補充練習
import re
print(re.findall("\w+)>\w+(?P=tag_name)>","
hello
")) #['h1']print(re.search("\w+)>\w+(?P=tag_name)>","
hello
").group()) #hello
print(re.search("\w+)>\w+(?P=tag_name)>","hello
").groupdict()) #hello
print(re.search(r"\w+(\w+)>","hello
").group())print(re.search(r"\w+\1>","
hello
").group())View Code
4)findall和search的區別
#為何同樣的表達式search與findall卻有不同結果:
print(re.search('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)
print(re.findall('\(([\+\-\*\/]*\d+\.?\d*)+\)',"1-12*(60+(-40.35/5)-(-4*3))")) #['/5', '*3']
#看這個例子:(\d)+相當于(\d)(\d)(\d)(\d)...,是一系列分組
print(re.search('(\d)+','123').group()) #group的作用是將所有組拼接到一起顯示出來
print(re.findall('(\d)+','123')) #findall結果是組內的結果,且是最后一個組的結果
search與findall
View Code
5)計算器會用到的技術點,例,1+(2+(3+4)*2
# # 計算第一步,判斷是否有括號
# inpp= '1+2+(3+4)*2'# b= re.search('\(',inpp)
# print(b) # 打印結果,判斷是字符串是否有()
# # 計算第二步,拿到最里面括號的內容
# inpp= '1+(2+(3+4*2))*2+(2+3)'# b= re.search('\([^()]+\)',inpp).group()
# print(b) # 拿到最里面括號的結果,結果靠前
# ## 計算第三步,拿到括號內的結果,先匹配乘除運算,并得到運算結果
# # # 匹配字符串中的'(3+42.2*2)',42.2*2 ,也可匹配,4*2,42 * 2# innp= '(3+2.2*2.3)'# # a= re.search('\d+\.?\d*\*\d+',innp).group() # 2.2*2,不能匹配2.2*2.3# a= re.search('\d+\.?\d*[*/]\d+\.?\d*',innp).group() # 可匹配到 2.2*2.3 或 2.2/1.1# print(a) #2.2*2# x ,y= re.split('[*/]',a)
# print(type(x),x,y)
# z= float(x) * float(y)
# z=str(z)
# s=innp.replace(a,z)
# print(s) # 結果就由 innp= '(3+2.2*2.3)' 變成了 (3+5.06)
View Code
6)過濾文件內的所有ip地址
import re
with open('hosts','r') asf:for line inf.readlines():
result2= re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}', line)if not result2 ==[]:
print result2[0]
result= result2[0] + '\n'with open('hosts_ip', 'a+') asw:
w.write(result)
五、時間模塊time
1)三種時間格式
print(time.time()) # 時間戳
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 格式化字符串時間,標準時間格式
print(time.strftime('%Y-%m-%d %X')) # 上面的簡寫
print(time.localtime()) # 結構化時間,東八區時間,把時間拆分成一小塊
print(time.gmtime()) # 結構化時間,世界標準時間,把時間拆分成一小塊
View Code
2)格式化時間的參數
%a Locale’s abbreviated weekday name.%A Locale’s full weekday name.%b Locale’s abbreviated month name.%B Locale’s full month name.%c Locale’s appropriate date and time representation.%d Day of the month as a decimal number [01,31].%H Hour (24-hour clock) as a decimal number [00,23].%I Hour (12-hour clock) as a decimal number [01,12].%j Day of the year as a decimal number [001,366].%m Month as a decimal number [01,12].%M Minute as a decimal number [00,59].%p Locale’s equivalent of either AM or PM. (1)%S Second as a decimal number [00,61]. (2)%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)%w Weekday as a decimal number [0(Sunday),6].%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)%x Locale’s appropriate date representation.%X Locale’s appropriate time representation.%y Year without century as a decimal number [00,99].%Y Year with century as a decimalnumber.%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].%Z Time zone name (no characters ifno time zone exists).%% A literal '%' character.
View Code
3)三種時間的轉換
# 結構化時間轉換成時間戳
print(time.localtime())
print(time.mktime(time.localtime()))
# 時間戳轉換成結構化時間
print(time.gmtime(123454))
# 結構化時間轉換成字符串標準時間
print(time.strftime('%Y-----%m',time.localtime()))
# 標準時間格式轉換成結構化時間
print(time.strptime('2017-03-01','%Y-%m-%d'))
View Code
4)結構化時間,時間戳,與英文顯示時間的轉換
# 轉換成 Sun May 20 10:03:11 2018這種類型
print(time.asctime(time.localtime()))
print(time.ctime(123456))
View Code
六、datatime模塊
1)獲取當前時間,時間戳轉換成標準時間
import datetime
print(datetime.datetime.now()) # 獲取當前時間
print(datetime.datetime.fromtimestamp(123123)) # 時間戳直接轉換成格式化標準時間
View Code
2)運算時間
import datetime
print(datetime.datetime.now()+ datetime.timedelta(days=3))
print(datetime.datetime.now()+ datetime.timedelta(weeks=3))
print(datetime.datetime.now()+ datetime.timedelta(hours=-3))
print(datetime.datetime.now()- datetime.timedelta(hours=3))
View Code
3)替換部分時間內容
print(datetime.datetime.now().replace(year=1999,hour=3))
View Code
4)時間運算
import datetime
event_start_time= '2019-12-01T17:00:00.000Z'event_start_time= datetime.datetime.strptime(event_start_time, "%Y-%m-%dT%H:%M:%S.%fZ") +datetime.timedelta(
hours=8)
print(event_start_time) #2019-12-02 01:00:00
七、random隨機數模塊
1)random模塊基本操作
import random
print(random.random())#(0,1)----float大于0且小于1之間的小數
print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之間的整數
print(random.randrange(1,3)) #[1,3) 大于等于1且小于3之間的整數
print(random.uniform(1,3)) #大于1小于3的小數,如1.927109612082716print(random.choice([1,'23',[4,5]])) #1或者23或者[4,5]
print(random.sample([1,'23',[4,5]],2)) #列表元素任意2個組合
item=[1,3,5,7,9]
random.shuffle(item) #打亂item的順序,相當于"洗牌"print(item)
View Code
2)隨機生成驗證碼,用了ASCII表的
import random
# 思路,先個隨機生成一個數字和字母,然后再隨機選擇其中一個
def make_code(n):
res=''
for i inrange(n):
s1=str(random.randint(0,9))
s2=chr(random.randint(65,90))
res+=random.choice([s1,s2])returnres
print(make_code(5))
View Code
八、os 模塊,與操作系統交互的模塊
1)os的基本參數,也基本功能
os.cpu_count() 獲取計算器的cpu核數
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下為"\t\n",Linux下為"\n"os.pathsep 輸出用于分割文件路徑的字符串 win下為;,Linux下為:
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.path.getsize(path) 返回path的大小
View Code
2)os的基本練習
import os
print(os.listdir(r'.')) # 顯示當前目錄下的所有文件,用列表的方式顯示
print(os.stat('tatata.py')) # 顯示該文件的詳細信息
print(os.stat('tatata.py').st_size) # 獲取文件大小,字節單位
print(os.path.getsize(r'tatata.py')) # 獲取文件大小,字節單位
# tasklist 是Windows下的命令,顯示當前所有的進程數
res=os.system('tasklist')
print('res---->',res) # res只是命令的執行成功與否的標志
os.environ['login']='yes'# 添加系統環境變量
print(os.environ['login'])
print(os.path.split('/a/b/c/d.txt')) # 把完整文件拆分成路徑,和文件名,拆分結果返回元組的形式
print(os.path.split('/a/b/c/d.txt')[0])
print(os.path.split('/a/b/c/d.txt')[1])
# 更方便的方式獲取到文件路徑和文件名
print(os.path.dirname('/a/b/c/d.txt'))
print(os.path.basename('/a/b/c/d.txt'))
# join 拼接路徑,注意點
print(os.path.join('a','b','D:\\','c','d.txt')) # D:\c\d.txt
print(os.path.join('a','b','d','c','/','d.txt')) # /d.txt
print(os.path.normcase('C:/windOws\\system32\\') ) # 只在Windows系統有用,c:\windows\system32\ ,大寫換小寫,左斜杠換右斜杠
print(os.path.normpath('c:\\windOws/a/b/../system32\\') ) #c:\\windOws/a/system32\\ # 規范路徑,去掉 .. 或者.
# 獲取上一級的上一級的目錄的2種方式,類似也項目目錄
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(os.path.normpath(
os.path.join(
os.path.abspath(__file__),'..','..')
))
View Code
os.system("test.exe") # 調用操作系統應用程序
九、 subprocess模塊,調用操作系統命令,可將命令的結果存放起來
import subprocess
obj=subprocess.Popen('ipconfig /all',
shell=True,
stdout=subprocess.PIPE, # 正確結果
stderr=subprocess.PIPE # 錯誤結果
)
print(obj.stdout.read().decode('gbk'))
View Code
十、sys模塊
1)常用操作
sys.argv 命令行參數List,第一個元素是程序本身路徑
sys.exit(n) 退出程序,正常退出時exit(0)
sys.version 獲取Python解釋程序的版本信息
sys.maxint 最大的Int值
sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform 返回操作系統平臺名稱
View Code
2)打印進度條
思路,方法
# import time
# # 打印進度條件
# print('\r[# ]',end='')
# time.sleep(0.5)
# print('\r[### ]',end='')
# time.sleep(0.5)
#
# print('\r[######## ]',end='')
# time.sleep(0.5)
#
# print('\r[######### ]',end='')
# print('[%-50s]' %'#')
# print('[%-50s]' %'##')
# print('[%-50s]' %'###')
# print('[%-50s]' %'####')
# print('[%-50s]' % (int(0.3*50) * '#'))
# print('[%-50s]' % (int(1*50) * '#'))
# print('%d%%' %30)
View Code
模擬打印進度條
import time
def progress(percent,width=50):if percent > 1:
percent= 1show_str=('[%%-%ds]' %width) %(int(percent*width) * '#')
print('\r%s %d%%' %(show_str,int(100 * percent)),end='')
total_size=102500recv_size=0
while recv_size
# 接收數據
time.sleep(0.1)
recv_size+=1024percent=recv_size /total_size
progress(percent)
View Code
3)獲取到執行腳本的傳入參數
import sys
print(sys.argv)
python cpu_test.py run
['cpu_test.py', 'run']? 已獲取到該參數
十一、shutil模塊。高級的 文件、文件夾、壓縮包 處理模塊
1)將文件內容拷貝到另一個文件中
import shutil
shutil.copyfileobj(open('a.xml','r'), open('new.xml', 'w'))
View Code
2)拷貝文件
shutil.copyfile('f1.log', 'f2.log')
View Code
3)僅拷貝權限。內容、組、用戶均不變
shutil.copymode('f1.log', 'f2.log')
View Code
4)僅拷貝狀態的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log')
View Code
5)拷貝文件和權限
shutil.copy('f1.log', 'f2.log')
View Code
6)拷貝文件和狀態信息
shutil.copy2('f1.log', 'f2.log')
View Code
7)遞歸的拷貝文件夾
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
View Code
8)拷貝軟連接
import shutil
shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
View Code
9)遞歸的刪除文件
import shutil
shutil.rmtree('folder1')
View Code
10)遞歸的去移動文件,它類似mv命令,其實就是重命名。
shutil.move('folder1', 'folder3')
View Code
11)打包與解壓
import shutil
#將/data 下的文件打包放置當前程序目錄
ret= shutil.make_archive("data_bak", 'gztar', root_dir='/data')
#將/data下的文件打包放置 /tmp/目錄
ret= shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')
View Code
打包和解壓的原理,shutil 對壓縮包的處理是調用 ZipFile 和 TarFile 兩個模塊來進行的
import zipfile
# 壓縮
z= zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()
# 解壓
z= zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()
zipfile的壓縮和解壓
import tarfile
# 壓縮>>> t=tarfile.open('/tmp/egon.tar','w')>>> t.add('/test1/a.py',arcname='a.bak')>>> t.add('/test1/b.py',arcname='b.bak')>>>t.close()
# 解壓>>> t=tarfile.open('/tmp/egon.tar','r')>>> t.extractall('/egon')>>> t.close()
tarfile的壓縮和解壓
十二、xml模塊
在json模塊之前,大都使用xml模塊來進行數據交換。xml數據如下
2
2008
141100
5
2011
59900
69
2011
13600
a.xml
xml協議在各個語言里的都 是支持的,在python中可以用以下模塊操作xml:
import xml.etree.ElementTree asET
tree= ET.parse("a.xml")
root=tree.getroot()
print(root.iter('year')) #全文搜索
print(root.find('country')) #在root的子節點找,只找一個
print(root.findall('country')) #在root的子節點找,找所有
View Code
1)輸入一個標簽的各個部分的內容
import xml.etree.ElementTree asET
tree= ET.parse("a.xml")
root=tree.getroot()
print(root.tag) # 跟,標簽名
print(root.attrib) # 屬性
print(root.text) # 文本內容
View Code
2)各種查找方式
import xml.etree.ElementTree asET
tree= ET.parse("a.xml")
root=tree.getroot()
res=root.iter('year') # 從整個樹形結構中尋找
# print(list(res))for item inres:
print(item.tag,item.attrib,item.text)
res=root.find('country').find('year') # 從當前節點的兒子中查找,找到第一個
print(res,res.text)
res=root.findall('country') # 從當前節點的兒子中查找,找到所有
print(res)
View Code
3)遍歷整個文件
# 遍歷for country in root: # root.iter('country)
print('==============>',country.tag,country.attrib)for item incountry:
print(item.tag,item.attrib,item.text)
View Code
4)修改文件內容
# 修改文件內容for year in root.iter('year'):
print(year.text)
year.text=str(int(year.text) + 1)
print(year.text)
year.attrib={'updated':'yes'} # 增加屬性
tree.write('a.xml')
View Code
5)之上,刪除year的屬性
# 刪除選中的屬性for year in root.iter('year'):
year.attrib.pop('updated')
tree.write('a.xml')
View Code
6)刪除節點
# 刪除節點for country inroot:
rank=country.find('rank')
v=int(rank.text)if v > 50:
# print(rank.text)
root.remove(country)
tree.write('a.xml')
View Code
7)增加一個標簽
# 增加一個標簽for country inroot:
tag=ET.Element('egon')
tag.attrib={'age':"1",'sex':'male'}
tag.text='tearcher'country.append(tag)
tree.write('a.xml')
View Code
十三、shelve模塊,作用類似于pickle模塊,同樣只支持python類型,操作更簡單
import shelve
# userinfo={
#'egon':{'age':18,'sex':'male'},
#'alex':{'age':38,'sex':'female'},
# }
f=shelve.open(r'sheve.txt',writeback=True)
f['egon']={'age':18,'sex':'male'}
f['alex']={'age':38,'sex':'female'}
f['egon']['age']=20# 修改
print(f['egon']['age'])
f.close()
View Code
十四、configparser 解析配置文件的模塊,如 my.ini。類似也mysql的配置文件
[egon]
pwd=123age=18salary=3.1is_beautiful=True
[alex]
pwd=3714age=38salary=3.2
my.ini
1)查看配置文件的內容
import configparser
config=configparser.ConfigParser()
config.read('my.ini')
print(config.sections()) # 查看所有的標題
print(config.options('egon')) # 取出該標題下的所有key
v1=config.get('egon','age') # 取出key的值
print(v1,type(v1))
v2=config.getint('egon','age') # 直接被轉換成整形
print(v2,type(v2))
v3=config.getfloat('egon','salary')
print(v3,type(v3))
v4=config.getboolean('egon','is_beautiful')
print(v4,type(v4))
View Code
2)修改配置文件的內容
import configparser
config=configparser.ConfigParser()
config.read('a.cfg',encoding='utf-8')
#刪除整個標題section2
config.remove_section('section2')
#刪除標題section1下的某個k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')
#判斷是否存在某個標題
print(config.has_section('section1'))
#判斷標題section1下是否有user
print(config.has_option('section1',''))
#添加一個標題
config.add_section('egon')
#在標題egon下添加name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #報錯,必須是字符串
#最后將修改的內容寫入文件,完成最終的修改
config.write(open('a.cfg','w'))
View Code
3)基于修改的內容的方法,自動創建 ini 文檔
import configparser
config=configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45','Compression': 'yes','CompressionLevel': '9'}
config['bitbucket.org'] ={}
config['bitbucket.org']['User'] = 'hg'config['topsecret.server.com'] ={}
topsecret= config['topsecret.server.com']
topsecret['Host Port'] = '50022'# mutates the parser
topsecret['ForwardX11'] = 'no'# same here
config['DEFAULT']['ForwardX11'] = 'yes'with open('example.ini', 'w') asconfigfile:
config.write(configfile)
View Code
十五、psutil模塊使用,監控服務器cpu內存模塊
import psutil
def cpu ():
cpu_count=psutil.cpu_count(False)
cpu_per= int(psutil.cpu_percent(1))
print(cpu_per)
print(cpu_count)return cpu_per
View Code
https://www.cnblogs.com/saneri/p/7528283.html
十六、openpyxl 模塊的使用。xlsx文件的簡單應用
#coding:utf-8
importosimportopenpyxlfrom openpyxl importWorkbookclassXlsxApi():defxlsx_info(self):
wb= openpyxl.load_workbook('chart_info.xlsx')
sh= wb['Sheet1']for cases in list(sh.rows)[1:]:
project= cases[1].value
service= cases[2].value
version= cases[3].valueprint(project,service,version)defxlsx_save(self,savefile):if notos.path.exists(savefile):
wb=Workbook()
ws=wb.active
ws.append([1, 2, 3])
wb.save(savefile)if __name__ == "__main__":
res=XlsxApi()
res.xlsx_save('文件名稱.xlsx')
View Code
十七、python模塊總篇
常用重要模塊
time 時間模塊
datatime 模塊
socket 網絡套接字
logging 日志模塊
hash 加密算法
re 正則模塊
random 隨機數模塊
shutil 文件、文件夾、壓縮包 處理模塊
與服務器相關運行模塊,運維腳本開發
os 與操作系統交互的模塊,添加環境變量
psutil 查看服務器的cpu,內存的模塊
sys 常用查看系統路徑,系統變量
paramiko 與服務器連接的模塊
subprocess 調用操作系統命令
pymysql 服務庫連接
配置文件解析模塊
xml 解析Java配置文件
configparser 解析配置文件
數據封裝傳輸模塊
json 封裝數據傳輸
pickle 封裝數據傳輸
shelve模塊,作用類似于pickle模塊,同樣只支持python類型,操作更簡單
web框架類
django
tornado
flask
bottle
爬蟲類
scrapy 爬蟲框架
requests 爬蟲,模擬請求
beautisoup 正則分析前端字符串
并發編程相關
Process 進程
Thread 線程
圖形化模塊
Seaborn 圖形可視化庫
matplotlib 圖形可視化
numpy 科學計算庫,類似于操作三維列表
tkinter GUI編程模塊
原文出處:http://www.cnblogs.com/linhaifeng/articles/6384466.html#_label4
總結
以上是生活随笔為你收集整理的python的主要应用领域及常用的函数模块_python之常用模块篇5的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab 折线图_MATLAB作图实
- 下一篇: python继承编程教程_Python实