Python常用模塊函數代碼匯總解析
一、文件和目錄操作
創建、刪除、修改、拼接、獲取當前目錄、遍歷目錄下的文件、獲取文件大小、修改日期、判斷文件是否存在等。略
二、日期和時間(內置模塊:time、datatime、calendar)
1.time.time() #返回自1970年1月1日0點到當前時間經過的秒數
實例1:獲取某函數執行的時間,單位秒
import timebefore = time.time()func1after = time.time()print(f'調用func1,花費時間{after-before}')
2.datetime.now() #返回當前時間對應的字符串
from datetime import datetimeprint(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協議下載)1)mac上安裝wget命令:brew install wget
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 oscmd = ’wget http://mirrors.sohu.com/nginx/nginx-1.13.9.zip’os.system(cmd)---version = input(’請輸入安裝包版本:’)cmd = fr’d:toolswget 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 Popenproc = Popen( args=’wget http://xxxxserver/xxxx.zip’, shell=True )
使用subprocess不需要等外部程序執行結束,可以繼續執行其他程序
四、多線程
如果是自動化測試用例編寫,可以使用pytest測試框架,自帶多線程實現方法。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: