Python全棧開發之經常使用模塊

No.1 sys

sys模塊是與Python解釋器交互的一個接口node

  • sys.argv 命令行參數List,第一個元素是程序自己路徑
  • sys.exit(n) 退出程序,正常退出時exit(0),錯誤退出sys.exit(1)
  • sys.version 獲取Python解釋程序的版本信息
  • sys.path 返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
  • sys.platform 返回操做系統平臺名稱

No.2 os

os模塊是與操做系統交互的一個接口python

  • 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.popen("bash command).read() 運行shell命令,獲取執行結果
  • os.environ 獲取系統環境變量
  • os.path.abspath(path) 返回path規範化的絕對路徑 os.path.split(path) 將path分割成目錄和文件名二元組返回 os.path.dirname(path) 返回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的大小

No.3 re

re模塊的使用過程c++

# 導入re模塊
import re
# 使用match方法進行匹配操做
result = re.match(正則表達式,要匹配的字符串)
# 若是上一步匹配到數據的話,可使用group方法來提取數據
result.group()

匹配單個字符正則表達式

字符 功能
. 匹配任意1個字符(除了\n)
[ ] 匹配[ ]中列舉的字符
\d 匹配數字,即0-9
\D 匹配非數字,即不是數字
\s 匹配空白,即 空格,tab鍵
\S 匹配非空白
\w 匹配單詞字符,即a-z、A-Z、0-九、_
\W 匹配非單詞字符

匹配多個字符shell

字符 功能
* 匹配前一個字符出現0次或者無限次,便可有可無
+ 匹配前一個字符出現1次或者無限次,即至少有1次
? 匹配前一個字符出現1次或者0次,即要麼有1次,要麼沒有
{m} 匹配前一個字符出現m次
{m,n} 匹配前一個字符出現從m到n次

匹配開頭或結尾編程

字符 功能
^ 匹配字符串開頭
$ 匹配字符串結尾

匹配分組json

字符 功能
| 匹配左右任意一個表達式
(ab) 將括號中字符做爲一個分組
\num 引用分組num匹配到的字符串
(?P<name>) 分組起別名
(?P=name) 引用別名爲name分組匹配到的字符串

match 僅僅查找第一個位置,若是找不到,返回Nonewindows

import re
result = re.match("kernel","kernel.cn")
result.group()result = re.match("kernel","kernel.cn")
result.group() # kernel

serach 僅僅返回一個結果bash

import re
ret = re.search(r"\d+", "閱讀次數爲 9999")
ret.group() # 9999

findall 返回最多能匹配的個數app

import re

ret = re.findall(r"\d+", "python = 9999, c = 7890, c++ = 12345")
print(ret) # ['9999', '7890', '12345']

sub 將匹配到的數據進行替換

import re

ret = re.sub(r"\d+", '998', "python = 997")
print(ret) # Python = 998

貪婪和非貪婪

正則表達式模式中使用到通配字,那它在從左到右的順序求值時,會盡可能抓取知足匹配最長字符串,在咱們上面的例子裏面,+會從字符串的啓始處抓取知足模式的最長字符,其中包括咱們想獲得的第一個整型字段的中的大部分,\d+只需一位字符就能夠匹配,而+則匹配了從字符串起始符合規則的全部字符,解決方式就是非貪婪操做符?,這個操做符能夠用在*、+、?的後面,要求正則匹配的越少越好

r的做用

Python中字符串前面加上 r 表示原生字符串,與大多數編程語言相同,正則表達式裏使用"\"做爲轉義字符,這就可能形成反斜槓困擾,假如你須要匹配文本中的字符"\",那麼使用編程語言表示的正則表達式裏將須要4個反斜槓"\":前兩個和後兩個分別用於在編程語言裏轉義成反斜槓,轉換成兩個反斜槓後再在正則表達式裏轉義成一個反斜槓,Python裏的原生字符串很好地解決了這個問題,有了原生字符串,你不再用擔憂是否是漏寫了反斜槓,寫出來的表達式也更直

No.4 time

時間處理模塊

time模塊的幾種轉換方式

  • time.time() 時間戳
  • time.strftime("%Y-%m-%d %X") 格式化的時間字符串
  • time.localtime() 本地時區的struct_time
  • time.gmtime() UTC時區的struct_time

時間戳轉換爲結構化時間

  • now_time = time.time() 時間戳
  • struct_time = time.localtime(now_time) 時間戳轉換爲結構化時間

結構化時間轉化爲時間戳

  • struct_time = time.localtime(time.time()) 結構化時間
  • now_time = time.mktime(struct_time) 結構化時間轉換爲時間戳

結構化時間轉化爲字符串時間

  • struct_time = time.localtime(time.time()) 結構化時間
  • str_time = time.strftime("%Y-%m-%d",struct_time) 結構化時間轉換爲字符串時間

字符串時間轉化爲結構化時間

  • str_time = "2018-04-17" 字符串時間
  • struct_time = time.strptime(str_time,"%Y-%m-%d") 字符串時間轉換爲結構化時間

No.5 timedate

日期處理模塊

  • timedate.date.today() 輸出日期
  • timedate.date.fromtimestamp() 接收時間戳,轉換成日期
  • timedate.current_time() 輸出日期時間毫秒值
  • timedate.current_time.timetuple() 將日期時間毫秒值轉換成struct_time
  • timedate.current_time.replace() 替換日期

No.6 json

只能適用於Python的基本數據類型,跨語言

  • json.loads() 接收一個字符串,轉換成Python數據類型
  • json.load() 從文化中讀取字符串,轉換成Python數據類型
  • json.dumps() 接收一個Python數據類型。轉換成字符串
  • json.dump() 接收一個Python數據類型,轉換成字符串,寫入到文件中

No.7 pickle

適用於Python的全部數據類型,可是隻針對Python

  • pickle.loads() 接收字節,轉換成Python數據類型
  • pickle.load() 從文化中讀取字節,轉換成Python數據類型
  • pickle.dumps() 接收一個Python數據類型。轉換成字節
  • pickle.dump() 接收一個Python數據類型,轉換成字節,寫入到文件中

No.8 logging

日誌處理模塊

日誌的級別
默認狀況下Python的logging模塊將日誌打印到了標準輸出中,且只顯示了大於等於WARNING級別的日誌,這說明默認的日誌級別設置爲WARNING(日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG)

日誌的配置

logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')

配置參數

  • logging.basicConfig() 函數中可經過具體參數來更改logging模塊默認行爲,可用參數有:
  • filename:用指定的文件名建立FiledHandler,這樣日誌會被存儲在指定的文件中。
  • filemode:文件打開方式,在指定了filename時使用這個參數,默認值爲「a」還可指定爲「w」。
  • format 指定handler使用的日誌顯示格式。
  • datefmt:指定日期時間格式。
  • level:設置rootlogger(後邊會講解具體概念)的日誌級別
  • stream:用指定的stream建立StreamHandler。能夠指定輸出到sys.stderr,sys.stdout或者* 文件(f=open(‘test.log’,’w’)),默認爲sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。
    format參數中可能用到的格式化串:
  • %(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 用戶輸出的消息

logger對象配置

logger = logging.getLogger('kernel') # 建立logging對象
logger.setLevel(logging.DEBUG) # 指定全局被處理消息級別(全局處理消息級別要高於或等於局部消息處理級別)

ch = logging.StreamHandler() # 屏幕流
ch.setLevel(logging.DEBUG) # 指定局部被處理消息級別

fh = logging.FileHandler("access.log") # 文件流
fh.setLevel(logging.WARNING) # 指定局部被處理消息級別

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 建立時間格式

ch.setFormatter(formatter) # 設置屏幕流時間格式
fh.setFormatter(formatter) # 設置文本流時間格式

logger.addHandler(ch) # 將屏幕流對象添加到logger中
logger.addHandler(fh) # 將文本流對象添加到logger中

logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

No.9 hashlib

加密模塊

obj = hashlib.md5() # 建立hashlib對象
obj = hashlib.md5(bytes('kernel',encoding='utf-8')) # 建立hashlib對象並加言
obj.update(bytes('hello',encoding='utf-8')) # 加密
ret = obj.hexdigest() # 獲取密文

No.10 configparser

操縱配置文件模塊

import configparser
cfg = configparser.ConfigParser() # 建立configparser對象
cfg.read('conf',encoding='utf-8') # 讀取配置文件

secs = cfg.sections() # 獲取全部節點
print(secs)

options = cfg.options(secs[0]) # 獲取指定節點的全部key
print(options)

item = cfg.items(secs[0]) # 獲取指定節點的鍵值對組合
print(item)

val = cfg.get(secs[0],options[0]) # 獲取指定節點下的指定key的值
print(val)

sec = cfg.remove_section(secs[0]) # 刪除指定節點
cfg.write(open('conf','w'))
print(sec)

sec = cfg.has_section('jiedian1') # 檢查是否存在該節點
print(sec)
sec = cfg.add_section('jiedian1') # 添加該節點
cfg.write(open('conf','w'))
print(sec)

cfg.set(secs[0],options[0],'111') # 修改指定節點下指定key的值
cfg.write(open('conf','w'))

cfg.remove_option(secs[0],options[0]) # 刪除指定節點下指定鍵值對
cfg.write(open('conf','w'))

No.11 XML

from xml.etree import ElementTree as ET
from xml.dom import minidom

# 修改XML
"""
解析XML的方式有兩種
1.解析字符串方式
將字符串解析成XML對象,root代指XML文件的根節點
str_xml = open('xo.xml', 'r').read()
root = ET.XML(str_xml)
2.解析文件方式
獲取xml文件的根節點
tree = ET.parse("xo.xml")
root = tree.getroot()
"""

# 遍歷XML的全部內容
et = ET.parse('conf.xml')
root = et.getroot() # 獲取根節點
print(root)

print(root.tag) # 頂層標籤

for child in root: # 遍歷XML文檔的第二層
    print(' ' + child.tag,child.attrib) # 第二層節點的標籤名和標籤屬性
    for i in child: # 遍歷XML文檔的第三層
        print('     ' + i.tag,i.attrib) # 第三層節點的標籤名和標籤屬性
        print('         ' + str(i.text)) # 第三層節點的屬性

# 遍歷XML的指定節點
for node in root.iter('year'): # 遍歷XML的全部year節點
    print(node.tag, node.text) # 節點的標籤名稱和內容

# 節點的標籤名稱和內容並修改節點內容
for node in root.iter('year'): # 遍歷XML的全部year節點
    print(node.tag, node.text) # 節點的標籤名稱和內容
    new_year = int(node.text) + 1 # 將year節點的內容增長1
    node.text = str(new_year)
    node.set('name', 'kernel') # 設置屬性和值
    node.set('age', '18')
    del node.attrib['name'] # 刪除屬性

# 刪除節點
for country in root.findall('country'): # 遍歷data下的全部country節點
    rank = int(country.find('rank').text) # 獲取每個country節點下rank節點的內容
    if rank > 50:
        root.remove(country)  # 刪除指定country節點

"""
保存XML文件的方式也有兩種
1.解析字符串方式
tree = ET.ElementTree(root)
tree.write("newnew.xml", encoding='utf-8')
2.解析文件方式
tree.write("new.xml",encoding='utf-8')
"""

# 建立XML文件
# 方式一
root = ET.Element("famliy")

son1 = ET.Element('son', {'name': '大兒子'}) # 建立大兒子節點
son2 = ET.Element('son', {"name": '二兒子'}) # 建立二兒子節點

grandson1 = ET.Element('grandson', {'name': '大孫子'}) # 在大兒子中建立兩個孫子
grandson2 = ET.Element('grandson', {'name': '二孫子'})

son1.append(grandson1) # 將孫子添加到兒子節點中
son1.append(grandson2)

root.append(son1) # 把兒子添加到根節點中
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

# 方式二
root = ET.Element("famliy")

son1 = root.makeelement('son', {'name': '大兒子'}) # 建立大兒子節點
son2 = root.makeelement('son', {"name": '二兒子'}) # 建立二兒子節點

grandson1 = root.makeelement('grandson', {'name': '大孫子'}) # 在大兒子中建立兩個孫子
grandson2 = root.makeelement('grandson', {'name': '二孫子'})

son1.append(grandson1) # 將孫子添加到兒子節點中
son1.append(grandson2)

root.append(son1) # 把兒子添加到根節點中
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

# 方式三
root = ET.Element("famliy")

son1 = root.SubElement('son', {'name': '大兒子'}) # 建立大兒子節點
son2 = root.SubElement('son', {"name": '二兒子'}) # 建立二兒子節點

grandson1 = root.SubElement('grandson', {'name': '大孫子'}) # 在大兒子中建立兩個孫子
grandson2 = root.SubElement('grandson', {'name': '二孫子'})

son1.append(grandson1) # 將孫子添加到兒子節點中
son1.append(grandson2)

root.append(son1) # 把兒子添加到根節點中
root.append(son1)

tree = ET.ElementTree(root)
tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) # short_empty_elements=False 表示控制元素的格式若是值爲False,沒有內容,它們是做爲一個單獨閉合的標籤,不然它們會以一對的形式發射開始/結束標記

# 方式四 原生保存的XML時默認無縮進,若是想要設置縮進的話,須要修改保存方式
def prettify(elem):
    """將節點轉換成字符串,並添加縮進。
    """
    rough_string = ET.tostring(elem, 'utf-8')
    reparsed = minidom.parseString(rough_string)
    return reparsed.toprettyxml(indent="\t")

root = ET.Element("famliy")

son1 = ET.Element('son', {'name': '大兒子'}) # 建立大兒子節點
son2 = ET.Element('son', {"name": '二兒子'}) # 建立二兒子節點

grandson1 = ET.Element('grandson', {'name': '大孫子'}) # 在大兒子中建立兩個孫子
grandson2 = ET.Element('grandson', {'name': '二孫子'})

son1.append(grandson1) # 將孫子添加到兒子節點中
son1.append(grandson2)

root.append(son1) # 把兒子添加到根節點中
root.append(son1)

raw_str = prettify(root)

f = open("xxxo.xml",'w',encoding='utf-8')
f.write(raw_str)
f.close()

No.12 subprocess

執行系統命令模塊

call 執行命令,返回狀態碼

  • ret = subprocess.call(["ls", "-l"], shell=False)
  • ret = subprocess.call("ls -l", shell=True)

check_call 執行命令,若是執行狀態碼是 0 ,則返回0,不然拋異常

  • subprocess.check_call(["ls", "-l"])
  • subprocess.check_call("exit 1", shell=True)

check_output 執行命令,若是狀態碼是 0 ,則返回執行結果,不然拋異常

  • subprocess.check_output(["echo", "Hello World!"])
  • subprocess.check_output("exit 1", shell=True)

subprocess.Popen(...) 用於執行復雜的系統命令

  • args:shell命令,能夠是字符串或者序列類型(如:list,元組)
  • bufsize:指定緩衝。0 無緩衝,1 行緩衝,其餘 緩衝區大小,負值 系統緩衝
  • stdin, stdout, stderr:分別表示程序的標準輸入、輸出、錯誤句柄
  • preexec_fn:只在Unix平臺下有效,用於指定一個可執行對象(callable object),它將在子進 程運行以前被調用
  • close_sfs:在windows平臺下,若是close_fds被設置爲True,則新建立的子進程將不會繼承父進程的輸入、輸出、錯誤管道。
  • close_sfs:在windows平臺下,若是close_fds被設置爲True,則新建立的子進程將不會繼承父進程的輸入、輸出、錯誤管道。
  • close_sfs:在windows平臺下,若是close_fds被設置爲True,則新建立的子進程將不會繼承父進程的輸入、輸出、錯誤管道,因此不能將close_fds設置爲True同時重定向子進程的標準輸入、輸出與錯誤(stdin, stdout, stderr)。
  • shell:同上
  • cwd:用於設置子進程的當前目錄
  • env:用於指定子進程的環境變量。若是env = None,子進程的環境變量將從父進程中繼承。
  • universal_newlines:不一樣系統的換行符不一樣,True -> 贊成使用 \n
  • startupinfo與createionflags只在windows下有效,將被傳遞給底層的CreateProcess()函數,用於設置子進程的一些屬性,如:主窗口的外觀,進程的優先級等等
import subprocess
"""
終端輸入的命令分爲兩種:
輸入便可獲得輸出,如:ifconfig
輸入進行某環境,依賴再輸入,如:python
"""
# 執行普通命令
ret1 = subprocess.Popen(["mkdir","t1"])
ret2 = subprocess.Popen("mkdir t2", shell=True)

# 在指定目錄上建立文件夾
obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)

# 依賴環境的命令
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")

out_error_list = obj.communicate()
print(out_error_list)

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out_error_list = obj.communicate('print("hello")')
print(out_error_list)
相關文章
相關標籤/搜索