Python常用模塊函數(shù)代碼匯總解析
一、文件和目錄操作
創(chuàng)建、刪除、修改、拼接、獲取當(dāng)前目錄、遍歷目錄下的文件、獲取文件大小、修改日期、判斷文件是否存在等。略
二、日期和時(shí)間(內(nèi)置模塊:time、datatime、calendar)
1.time.time() #返回自1970年1月1日0點(diǎn)到當(dāng)前時(shí)間經(jīng)過(guò)的秒數(shù)
實(shí)例1:獲取某函數(shù)執(zhí)行的時(shí)間,單位秒
import timebefore = time.time()func1after = time.time()print(f'調(diào)用func1,花費(fèi)時(shí)間{after-before}')
2.datetime.now() #返回當(dāng)前時(shí)間對(duì)應(yīng)的字符串
from datetime import datetimeprint(datetime.now())
輸出結(jié)果: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程序中調(diào)用其他程序
python中調(diào)用外部程序,使用標(biāo)準(zhǔn)庫(kù)os庫(kù)的system函數(shù)、或者subproprocess庫(kù)。
1.wget(wget是一個(gè)從網(wǎng)絡(luò)上自動(dòng)下載文件的自由工具,支持通過(guò) HTTP、HTTPS、FTP 三個(gè)最常見(jiàn)的 TCP/IP協(xié)議下載)1)mac上安裝wget命令:brew install wget
2)wget --help/wget -h
3)使用wget下載文件,下載文件至當(dāng)前目錄下,mac終端命令:wget http://mirrors.sohu.com/nginx/nginx-1.13.9.zip
2.os.system函數(shù)
1)os.system調(diào)用外部程序,必須等被調(diào)用程序執(zhí)行結(jié)束,才能繼續(xù)往下執(zhí)行
2)os.system 函數(shù)沒(méi)法獲取 被調(diào)用程序輸出到終端窗口的內(nèi)容
import oscmd = ’wget http://mirrors.sohu.com/nginx/nginx-1.13.9.zip’os.system(cmd)---version = input(’請(qǐng)輸入安裝包版本:’)cmd = fr’d:toolswget http://mirrors.sohu.com/nginx/nginx-{version}.zip’os.system(cmd)
3.subprocess模塊
實(shí)例1:將本該在終端輸出的信息用pipe獲取,并進(jìn)行分析
from subprocess import PIPE, Popen# 返回的是 Popen 實(shí)例對(duì)象proc = Popen( ’du -sh *’, stdin = None, stdout = PIPE, stderr = PIPE, shell=True)outinfo, errinfo = proc.communicate() # communicate 方法返回 輸出到 標(biāo)準(zhǔn)輸出 和 標(biāo)準(zhǔn)錯(cuò)誤 的字節(jié)串內(nèi)容outinfo = outinfo.decode(’gbk’)errinfo = errinfo.decode(’gbk’)outputList = outinfo.splitlines()print(outputList[0].split(’ ’)[0].strip())
實(shí)例2:?jiǎn)?dòng)wget下載文件
from subprocess import Popenproc = Popen( args=’wget http://xxxxserver/xxxx.zip’, shell=True )
使用subprocess不需要等外部程序執(zhí)行結(jié)束,可以繼續(xù)執(zhí)行其他程序
四、多線程
如果是自動(dòng)化測(cè)試用例編寫(xiě),可以使用pytest測(cè)試框架,自帶多線程實(shí)現(xiàn)方法。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java封裝數(shù)組實(shí)現(xiàn)包含、搜索和刪除元素操作詳解2. 淺談SpringMVC jsp前臺(tái)獲取參數(shù)的方式 EL表達(dá)式3. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)4. Gitlab CI-CD自動(dòng)化部署SpringBoot項(xiàng)目的方法步驟5. python基于socket模擬實(shí)現(xiàn)ssh遠(yuǎn)程執(zhí)行命令6. Django-migrate報(bào)錯(cuò)問(wèn)題解決方案7. JAVA上加密算法的實(shí)現(xiàn)用例8. 使用Python和百度語(yǔ)音識(shí)別生成視頻字幕的實(shí)現(xiàn)9. idea打開(kāi)多個(gè)窗口的操作方法10. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問(wèn)題……
