Python常用模組函式程式碼彙總解析
一、檔案和目錄操作
建立、刪除、修改、拼接、獲取當前目錄、遍歷目錄下的檔案、獲取檔案大小、修改日期、判斷檔案是否存在等。略
二、日期和時間(內建模組:time、datatime、calendar)
1.time.time() #返回自1970年1月1日0點到當前時間經過的秒數
例項1:獲取某函式執行的時間,單位秒
import time before = time.time() func1 after = time.time() print(f"呼叫func1,花費時間{after-before}")
2.datetime.now() #返回當前時間對應的字串
from datetime import datetime
print(datetime.now())
輸出結果:2020-06-27 15:48:38.400701
3.以指定格式顯示字串
datetime.now().strftime('%Y-%m-%d -- %H:%M:%S')
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
三、python程式中呼叫其他程式
python中呼叫外部程式,使用標準庫os庫的system函式、或者subproprocess庫。
1.wget(wget是一個從網路上自動下載檔案的自由工具,支援通過 HTTP、HTTPS、FTP 三個最常見的 TCP/IP協議下載)
2)wget --help/wget -h
3)使用wget下載檔案,下載檔案至當前目錄下,mac終端命令:wget http://mirrors.sohu.com/nginx/nginx-1.13.9.zip
2.os.system函式
1)os.system呼叫外部程式,必須等被呼叫程式執行結束,才能繼續往下執行
2)os.system 函式沒法獲取 被呼叫程式輸出到終端視窗的內容
import os cmd = 'wget http://mirrors.sohu.com/nginx/nginx-1.13.9.zip' os.system(cmd) --- version = input('請輸入安裝包版本:') cmd = fr'd:\tools\wget http://mirrors.sohu.com/nginx/nginx-{version}.zip' os.system(cmd)
3.subprocess模組
例項1:將本該在終端輸出的資訊用pipe獲取,並進行分析
from subprocess import PIPE,Popen # 返回的是 Popen 例項物件 proc = Popen( 'du -sh *',stdin = None,stdout = PIPE,stderr = PIPE,shell=True) outinfo,errinfo = proc.communicate() # communicate 方法返回 輸出到 標準輸出 和 標準錯誤 的位元組串內容 outinfo = outinfo.decode('gbk') errinfo = errinfo.decode('gbk') outputList = outinfo.splitlines() print(outputList[0].split(' ')[0].strip())
例項2:啟動wget下載檔案
from subprocess import Popen proc = Popen( args='wget http://xxxxserver/xxxx.zip',shell=True )
使用subprocess不需要等外部程式執行結束,可以繼續執行其他程式
四、多執行緒
如果是自動化測試用例編寫,可以使用pytest測試框架,自帶多執行緒實現方法。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。