python3常用標準庫趁著有時間,把一些我用過的常用標準庫進行整理和復習。 time
常用時間占位符
![]() time庫各方法關系 datetime雖然python庫中已經(jīng)有了time庫,但time庫不支持對時間的加減等操作,因此就有了datetime庫。
有了以上幾個方法,我們就可以對時間進行加減操作,并可以在time和datetime之間進行轉(zhuǎn)換。
import timeimport datetimedef main(): date1_string = "2017/6/8 15:0:0" # date1_string轉(zhuǎn)換為時間戳# strptime -> mktime -> fromtimestamp ==> datetime.datetime date1 = datetime.datetime.fromtimestamp(time.mktime( time.strptime(date1_string, '%Y/%m/%d %H:%M:%S'))) date2 = datetime.datetime.now()# 獲取當前時間 # 使用datetime.datetime對象之間 進行操作,結(jié)果為datetime.timedelta對象 result1 = date2 - date1# 兩個時間過了多久了 print(result1.days, result1.seconds) # datetime.datetime與datetime.timedelta之間的操作, 結(jié)果是datetime.datetime對象 year = datetime.timedelta(days=365) # 一年時間 result2 = date2 + 2 * year# 當前時間的兩年后 print(result2.year, result2.month, result2.day)if __name__ == '__main__': main() random使用random可以生成偽隨機數(shù)。
生成驗證碼例子: import randomdef make_code(n): res = '' for i in range(n): letter = chr(random.randint(65, 90))# 生成A-Z的任意一個字母 number = str(random.randint(0, 9))# 生成0-9的任意一個數(shù) res += random.choice([letter, number]) return res print(make_code(9)) syssys模塊提供了一些與解釋器相關的變量和函數(shù)。
os一般用于對文件和目錄進性操作的模塊。 路徑相關
文件/目錄操作
輸出符號
pathpath是os庫中的一個模塊,里面有很多實用的函數(shù)。
shutilshutil模塊提供了一系列對文件和文件集合的高階操作。 特別是提供了一些支持文件拷貝和刪除的函數(shù)。 拷貝操作
刪除操作
移動操作
jsonjson模塊可以把python基本數(shù)據(jù)類型與json數(shù)據(jù)進行轉(zhuǎn)換。
擴展json
import jsonclass Foo: def __init__(self, name, age): self.name = name self.age = age def data_dict(self): # 返回的是基本數(shù)據(jù)類型 return {"name": self.name, "age": self.age}class JsonCustomEncoder(json.JSONEncoder): # 重寫default方法 def default(self, field): if isinstance(field, Foo): return field.data_dict() # 調(diào)用自定義的方法 else: return json.JSONEncoder.default(self, field) f = Foo("lczmx", 21)# 使用時要指定自定義的編碼器res = json.dumps(f, cls=JsonCustomEncoder) print(res)# {"name": "lczmx", "age": 21} pickle模塊 pickle 實現(xiàn)了對一個 Python 對象結(jié)構(gòu)的二進制序列化和反序列化。它只能用于Python,并且可能不同版本的Python彼此都不兼容,因此,只能用Pickle保存那些不重要的數(shù)據(jù),不能成功地反序列化也沒關系。 注意:pickle 模塊并不安全。你只應該對你信任的數(shù)據(jù)進行unpickle操作. import pickle dic = {'name': 'alvin', 'age': 23, 'sex': 'male'} print(type(dic)) # <class 'dict'>j = pickle.dumps(dic) print(type(j)) # <class 'bytes'>f = open('序列化對象_pickle', 'wb') # 注意是w是寫入str,wb是寫入bytes,j是'bytes'f.write(j) # -------------------等價于pickle.dump(dic,f)f.close()# -------------------------反序列化f = open('序列化對象_pickle', 'rb') data = pickle.loads(f.read()) # 等價于data=pickle.load(f)print(data['age']) shelveshelve" 是一種持久化的類似字典的對象,只有open方法,比pickle簡單。 import shelve d = shelve.open("持久化文件.txt")# 以 d[key] = data 的形式存儲d["name"] = "lczmx"d["age"] = 22d["addr"] = "guangzhou"d["data"] = [1, 2, 3]# 使用中括號取值name = d["name"] print(name) # lczmx# 使用del刪除某個鍵對應的值del d["age"]# 可以使用 in 判斷某個鍵是否存在flag = "age" in d print(flag) # False# .keys()方法 可以列出所有的鍵 (速度較慢!)klist = list(d.keys()) print(klist) # ['name', 'addr', 'data']# 值即使是引用對象,假如要保存修改后的值,要重新賦值temp = d['data'] temp.append(4) print(d["data"]) # [1, 2, 3]d['data'] = temp print(d["data"]) # [1, 2, 3, 4]# close掉,可以使用上下文管理協(xié)議d.close() xmlxml也是一個可以跨語言的數(shù)據(jù)交換協(xié)議,但使用起來沒有json簡單,由于xml誕生的時間比json早,所以至今還有一些公司正在使用。 生成xml步驟:
import xml.etree.ElementTree as ET# 創(chuàng)建根節(jié)點new_xml = ET.Element("namelist")# 為跟節(jié)點創(chuàng)建字節(jié)點name1 = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"}) age1 = ET.SubElement(name1, "age", attrib={"checked": "no"})# 添加內(nèi)容name1.text = '老王'age1.text = "30"# 同上name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"}) age2 = ET.SubElement(name2, "age") name2.text = "隔壁"age2.text = '33'# 生成文檔對象et = ET.ElementTree(new_xml)# 寫入文件中et.write("test.xml", encoding="utf-8", xml_declaration=True)# 打印生成的格式ET.dump(new_xml) 結(jié)果: <?xml version='1.0' encoding='utf-8'?><namelist> <name enrolled="yes">老王<age checked="no">30</age></name> <name enrolled="no">隔壁<age>33</age></name></namelist> 讀取xml對xml文件進行操作,用的是 import xml.etree.ElementTree as ET tree = ET.parse("./test.xml") root = tree.getroot()
查看
遍歷/查找
修改
刪除
struct此模塊可以執(zhí)行 Python 值和以 Python bytes 對象表示的 C 結(jié)構(gòu)之間的轉(zhuǎn)換。 這可以被用來處理存儲在文件中或是從網(wǎng)絡連接等其他來源獲取的二進制數(shù)據(jù)。
import struct# 數(shù)據(jù) -> bytespi = 3.14159265358res = struct.pack("f", pi) print(res, type(res)) # b'\xdb\x0fI@' <class 'bytes'> # 已經(jīng)轉(zhuǎn)化為字節(jié)類型# bytes -> 原數(shù)據(jù)data = struct.unpack("f", res) print(data, type(data)) # (3.1415927410125732,) <class 'tuple'>
re正則表達式是用來描述字符或字符串的特殊符號,在python中用re模塊實現(xiàn),正則表達式模式被編譯成一系列的字節(jié)碼,用 C 編寫的匹配引擎執(zhí)行。 元字符正則表達式語言由兩種基本字符類型組成:原義(正常)文本字符和元字符,元字符實質(zhì)上就是有特殊含義的字符。
方法查找
分割
替換
匹配對象(
去括號優(yōu)先級 import re res = re.findall(r"(abc)+", "abcabcabc") print(res) # ['abc'] 其匹配結(jié)果是["abc"],而非["abcabcabc"],這是因為括號的優(yōu)先級高,假如要括號與后面的元字符相結(jié)合的化可以使用以下方法: import re res = re.findall(r"(?:abc)+", "abcabcabc") print(res) # ['abcabcabc'] 匹配原理 logging關于日志管理的基本教程,請點擊這里 關于使用日志的流程,大約有以下步驟:
注意 打印到終端打印到終端是開發(fā)過程中的一個實用的方法。 import logging logging.basicConfig() logging.debug("debug messages") logging.info("info messages") logging.warning("warning messages") logging.error("error messages") logging.critical("critical messages") 由于默認日志級別為WARNING,所以只在終端顯示了后三行信息 寫入文件為 import logging logging.basicConfig(filename="test.log") logging.debug("debug messages") logging.info("info messages") logging.warning("warning messages") logging.error("error messages") logging.critical("critical messages")
多模塊使用在多個模塊中 import loggingimport mylibdef main(): logging.basicConfig() logging.warning("start function") mylib.my_func() logging.warning("end function") print(id(logging))# 2248755624272if __name__ == '__main__': main() ./mylib.py # ./mylib.pyimport loggingdef my_func(): logging.error("error massage") print(id(logging))# 2248755624272 修改日志級別日志級別從低到高:
修改日志級別要用到 CRITICAL = 50FATAL = CRITICAL ERROR = 40WARNING = 30WARN = WARNING INFO = 20DEBUG = 10NOTSET = 0 例子: import logging logging.basicConfig(level=logging.INFO) logging.warning("start function") 從命令行中接收日志級別使用 import loggingimport argparse# log選項的值只能是level_list的元素level_list = ["debug", "info", "warning", "warn", "error", "fatal", "critical"] level_list.extend(list(map(lambda x: x.upper(), level_list)))# 全大寫再加入parser = argparse.ArgumentParser(description="test file") parser.add_argument("--log", default="debug", choices=level_list) args = parser.parse_args()# 拿到級別字符串后要大寫level = getattr(logging, args.log.upper()) logging.basicConfig(level=level) logging.debug("debug messages") logging.info("info messages") logging.warning("warning messages") logging.error("error messages") logging.critical("critical messages") $ python test.py --log error ERROR:root:error messages CRITICAL:root:critical messages $ python test.py --log info INFO:root:info messages WARNING:root:warning messages ERROR:root:error messages CRITICAL:root:critical messages configparserconfigparser庫是python的配置文件管理模塊,其所用結(jié)構(gòu)與 INI 文件的類似。 寫步驟:
import configparser# 1 創(chuàng)建parser對象config = configparser.ConfigParser()# 2 添加數(shù)據(jù)# 方法一config["DEFAULT"] = {"HOST": "localhost", "PORT": "3306"}# 方法二config["CUSTOM"] = {} config["CUSTOM"]["HOST"] = "192.168.0.1"# 或custom_config = config["CUSTOM"] custom_config["PORT"] = "3333"# 3 寫入文件with open("config.ini", "w") as f: config.write(f)
config.ini文件: [DEFAULT]host = localhostport = 3306[CUSTOM]host = 192.168.0.1port = 3333 讀注意:DEFAULT不在sections()中,可以直接用
刪操作
argparseargparse是python推薦的命令行參數(shù)解析模塊,argparse基于optparse(3.2版中已經(jīng)被棄用),所以兩者用法類似。
創(chuàng)建解析器parser = argparse.ArgumentParser(description="計算兩個數(shù)的和", prog="SUM")
添加參數(shù)使用
parser.add_argument("x", type=float, help="一個數(shù)x") # 添加位置參數(shù)xparser.add_argument("y", type=float, help="一個數(shù)y") # 添加位置參數(shù)y# 添加選項-a, 把值存儲為Trueparser.add_argument("-a", action="store_true", help="顯示詳細過程")# 添加選項-f,它的值知道能是[1, 2, 3]中的元素parser.add_argument("-f", default=1, choices=[1, 2, 3], type=int, help="保留小數(shù)點位數(shù)")# 添加選項-v 或 --version# 使用來自argparse.ArgumentParser的prog參數(shù)parser.add_argument("-v", "--version", action="version", version="%(prog)s 0.1", help="顯示版本") 解析參數(shù)通過 # 解析args = parser.parse_args() print(args.x) print(args.a) print(args.f) 完整例子一個計算兩個數(shù)和的程序 import argparse parser = argparse.ArgumentParser(description="計算兩個數(shù)的和", prog="SUM") parser.add_argument("x", type=float, help="一個數(shù)x") # 添加位置參數(shù)xparser.add_argument("y", type=float, help="一個數(shù)y") # 添加位置參數(shù)y# 添加選項-a, 把值存儲為Trueparser.add_argument("-a", action="store_true", help="顯示詳細過程")# 添加選項-f,它的值知道能是[1, 2, 3]中的元素parser.add_argument("-f", default=1, choices=[1, 2, 3], type=int, help="保留小數(shù)點位數(shù)")# 添加選項-v 或 --version# 使用來自argparse.ArgumentParser的prog參數(shù)parser.add_argument("-v", "--version", action="version", version="%(prog)s 0.1", help="顯示版本")# 解析args = parser.parse_args()# 計算并保留小數(shù)res = round(args.x + args.y, args.f)if args.a: print("{x} + {y} = {res}".format(x=args.x, y=args.y, res=res))else: print(res) 在命令行中使用: $ python get_sum.py -h usage: SUM [-h] [-a] [-f {1,2,3}] [-v] x y 計算兩個數(shù)的和 positional arguments: x 一個數(shù)x y 一個數(shù)y optional arguments: -h, --help show this help message and exit -a 顯示詳細過程 -f {1,2,3} 保留小數(shù)點位數(shù) -v, --version 顯示版本 $ python get_sum.py -v SUM 0.1 $ python get_sum.py 3.14 5.96 9.1 $ python get_sum.py 3.14 5.96 -a 3.14 + 5.96 = 9.1 $ python get_sum.py 3.14159 3.335 -f 3 -a 3.14159 + 3.335 = 6.477 $ python get_sum.py usage: SUM [-h] [-a] [-f {1,2,3}] [-v] x y SUM: error: the following arguments are required: x, y hashlibhashlib是針對不同的安全哈希和消息摘要算法實現(xiàn)了一個通用的接口。 生成md5 import hashlib md5 = hashlib.md5()# 輸入的是字節(jié)串md5.update("test message".encode("utf-8")) res = md5.hexdigest() print(res)# c72b9698fa1927e1dd12d3cf26ed84b2 為md5加鹽 import hashlib md5 = hashlib.md5()# 輸入的是字節(jié)md5.update("加鹽".encode("utf-8")) md5.update("test message".encode("utf-8")) res = md5.hexdigest() print(res)# 3f5a030db81d9e5e83d2c8e7eba1965c uuid生成uuid4 import uuid print(uuid.uuid4())# f1d50cdd-2f36-4db2-b788-ec4f2f08ce52 subprocesssubprocess 模塊允許你生成新的進程,連接它們的輸入、輸出、錯誤管道,并且獲取它們的返回碼。
更加詳細內(nèi)容,請看官方文檔 獲取返回信息
使用例子 import subprocess# 執(zhí)行沒有參數(shù)的subprocess.Popen(["dir"], shell=True, stdout=open("dir_res.txt", "w"))# 有參數(shù)# get_sum.py為argparse模塊最后的例子command = "python get_sum.py 3.47 2.48 -a -f 2"res2 = subprocess.Popen(command.split(" "), shell=True, stdout=subprocess.PIPE) print(res2.stdout.read().decode("gbk")) # 3.47 + 2.48 = 5.95# stdout作為stdinres3 = subprocess.Popen(["echo", "www.baidu.com"], shell=True, stdout=subprocess.PIPE) res4 = subprocess.Popen(["nslookup"], shell=True, stdin=res3.stdout, stdout=subprocess.PIPE) print(res4.stdout.read().decode("gbk"))""" 默認服務器: UnKnown Address: 192.168.0.1 > 服務器: UnKnown Address: 192.168.0.1 名稱: www.baidu.com Address: 182.61.200.7 > """
|
|