Python編寫(xiě)運(yùn)維進(jìn)程文件目錄操作實(shí)用腳本示例
Python在很大程度上可以對(duì)shell腳本進(jìn)行替代。筆者一般單行命令用shell,復(fù)雜點(diǎn)的多行操作就直接用Python了。這篇文章就歸納一下Python的一些實(shí)用腳本操作。
1. 執(zhí)行外部程序或命令
我們有以下C語(yǔ)言程序cal.c(已編譯為.out文件),該程序負(fù)責(zé)輸入兩個(gè)命令行參數(shù)并打印它們的和。該程序需要用Python去調(diào)用C語(yǔ)言程序并檢查程序是否正常返回(正常返回會(huì)返回 0)。
#include<stdio.h> #include<stdlib.h> int main(int argc, char* argv[]){ int a = atoi(argv[1]); int b = atoi(argv[2]); int c = a + b; printf("%d + %d = %d\n", a, b, c); return 0; }
那么我們可以使用subprocess
模塊的run
函數(shù)來(lái)spawn一個(gè)子進(jìn)程:
res = subprocess.run(["Python-Lang/cal.out", "1", "2"]) print(res.returncode)
可以看到控制臺(tái)打印出進(jìn)程的返回值0:
1 + 2 = 3
0
當(dāng)然,如果程序中途被殺死。如我們將下列while.c程序?qū)憺橄铝兴姥h(huán)(已編譯為.out文件):
#include<stdio.h> #include<stdlib.h> int main(int argc, char* argv[]){ while(1); return 0; }
我們同樣用run
函數(shù)接收其返回值:
res = subprocess.run("Python-Lang/while.out") print(res.returncode)
不過(guò)我們?cè)诔绦蜻\(yùn)行中用shell命令將其終止掉:
(base) orion-orion@MacBook-Pro Python-Lang % ps -a |grep while 11829 ttys001 0:17.49 Python-Lang/while.out 11891 ttys005 0:00.00 grep while (base) orion-orion@MacBook-Pro Python-Lang % kill 11829
可以看到控制臺(tái)打印輸出的進(jìn)程返回值為-15(因?yàn)樨?fù)值-N表示子進(jìn)程被信號(hào)N終止,而kill命令默認(rèn)的信號(hào)是15,該信號(hào)會(huì)終止進(jìn)程):
-15
如果程序陷入死循環(huán)不能正常終止,我們總不能一直等著吧?此時(shí),我們可以設(shè)置超時(shí)機(jī)制并進(jìn)行異常捕捉:
try: res = subprocess.run(["Python-Lang/while.out"], capture_output=True, timeout=5) except subprocess.TimeoutExpired as e: print(e)
此時(shí)會(huì)打印輸出異常結(jié)果:
Command '['Python-Lang/while.out']' timed out after 5 seconds
有時(shí)需要獲取程序的輸出結(jié)果,此時(shí)可以加上capture_output
參數(shù),然后訪問(wèn)返回對(duì)象的stdout
屬性即可:
res = subprocess.run(["netstat", "-a"], capture_output=True) out_bytes = res.stdout
輸出結(jié)果是以字節(jié)串返回的,如果想以文本形式解讀,可以再增加一個(gè)解碼步驟:
out_text = out_bytes.decode("utf-8") print(out_text)
可以看到已正常獲取文本形式的輸出結(jié)果:
... kctl 0 0 33 6 com.apple.netsrc kctl 0 0 34 6 com.apple.netsrc kctl 0 0 1 7 com.apple.network.statistics kctl 0 0 2 7 com.apple.network.statistics kctl 0 0 3 7 com.apple.network.statistics (base) orion-orion@MacBook-Pro Learn-Python %
一般來(lái)說(shuō),命令的執(zhí)行不需要依賴底層shell的支持(如sh,bash等),我們提供的字符串列表會(huì)直接傳遞給底層的系統(tǒng)調(diào)用,如os.execve()
。如果希望命令通過(guò)shell來(lái)執(zhí)行,只需要給定參數(shù)shell=True
并將命令以簡(jiǎn)單的字符串形式提供即可。比如我們想讓Python執(zhí)行一個(gè)涉及管道、I/O重定向或其它復(fù)雜的Shell命令時(shí),我們就可以這樣寫(xiě):
out_bytes = subprocess.run("ps -a|wc -l> out", shell=True)
2. 文件和目錄操作(命名、刪除、拷貝、移動(dòng)等)
我們想要和文件名稱和路徑打交道時(shí),為了保證獲得最佳的移植性(尤其是需要同時(shí)運(yùn)行與Unix和Windows上時(shí)),最好使用os.path
中的函數(shù)。例如:
import os file_name = "/Users/orion-orion/Documents/LocalCode/Learn-Python/Python-Lang/test.txt" print(os.path.basename(file_name)) # test.txt print(os.path.dirname(file_name)) # /Users/orion-orion/Documents/LocalCode/Learn-Python/Python-Lang print(os.path.split(file_name)) # ('/Users/orion-orion/Documents/LocalCode/Learn-Python/Python-Lang', 'test.txt') print(os.path.join("/new/dir", os.path.basename(file_name))) # /new/dir/test.txt print(os.path.expanduser("~/Documents")) # /Users/orion-orion/Documents
其中os.path.expanduser
當(dāng)用戶或$HOME
未知時(shí), 將不做任何操作。如我們這里的$HOME
就為/Users/orion-orion
:
(base) orion-orion@MacBook-Pro ~ % echo $HOME /Users/orion-orion
如果要?jiǎng)h除文件,請(qǐng)用os.remove
(在刪除前注意先判斷文件是否存在):
file_name = "Python-Lang/test.txt" if os.path.exists(file_name): os.remove(file_name)
接下來(lái)我們看如何拷貝文件。當(dāng)然最直接的方法是調(diào)用Shell命令:
os.system("cp Python-Lang/test.txt Python-Lang/test2.txt")
當(dāng)然這不夠優(yōu)雅。如果不像通過(guò)調(diào)用shell命令來(lái)實(shí)現(xiàn),可以使用shutil模塊,該模塊提供了一系列對(duì)文件和文件集合的高階操作,其中就包括文件拷貝和移動(dòng)/重命名。這些函數(shù)的參數(shù)都是字符串,用來(lái)提供文件或目錄的名稱。以下是示例:
src = "Python-Lang/test.txt" dst = "Python-Lang/test2.txt" # 對(duì)應(yīng)cp src dst (拷貝文件,存在則覆蓋) shutil.copy(src, dst) src = "Python-Lang/sub_dir" dst = "Python-Lang/sub_dir2" # 對(duì)應(yīng)cp -R src dst (拷貝整個(gè)目錄樹(shù)) shutil.copytree(src, dst) src = "Python-Lang/test.txt" dst = "Python-Lang/sub_dir/test2.txt" # 對(duì)應(yīng)mv src dst (移動(dòng)文件,可選擇是否重命名) shutil.move(src, dst)
可以看到,正如注釋所言,這些函數(shù)的語(yǔ)義和Unix命令類似。如果你對(duì)Unix下的文件拷貝/移動(dòng)等操作不熟悉,可以參見(jiàn)
http://www.dbjr.com.cn/article/231477.htm
http://www.dbjr.com.cn/article/183084.htm
默認(rèn)情況下,如果源文件是一個(gè)符號(hào)鏈接,那么目標(biāo)文件將會(huì)是該鏈接所指向的文件的拷貝。如果只想拷貝符號(hào)鏈接本身,可以提供關(guān)鍵字參數(shù)follow_symlinks:
shutil.copy(src, dst, follow_symlinks=True)
如果想在拷貝的目錄中保留符號(hào)鏈接,可以這么做:
shutil.copytree(src, dst, symlinks=True)
有時(shí)在拷貝整個(gè)目錄時(shí)需要對(duì)特定的文件和目錄進(jìn)行忽略,如.pyc
這種中間過(guò)程字節(jié)碼。我們可以為copytree
提供一個(gè)ignore函數(shù),該函數(shù)已目錄名和文件名做為輸入?yún)?shù),返回一列要忽略的名稱做為結(jié)果(此處用到字符串對(duì)象的.endswith
方法,該方法用于獲取文件類型):
def ignore_pyc_files(dirname, filenames): return [name for name in filenames if name.endswith('pyc')] shutil.copytree(src, dst, ignore=ignore_pyc_files)
不過(guò)由于忽略文件名這種模式非常常見(jiàn),已經(jīng)有一個(gè)實(shí)用函數(shù)ignore_patterns()
提供給我們使用了(相關(guān)模式使用方法類似.gitignore
):
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("*~", "*.pyc"))
注:此處的"*~"
模式匹配是文本編輯器(如Vi)產(chǎn)生的以"~"結(jié)尾的中間文件。
忽略文件名還常常用在os.listdir()
中。比如我們?cè)跀?shù)據(jù)密集型(如機(jī)器學(xué)習(xí))應(yīng)用中,需要遍歷data
目錄下的所有數(shù)據(jù)集文件并加載,但是需要排除.
開(kāi)頭的隱藏文件,如.git
,否則會(huì)出錯(cuò),此時(shí)可采用下列寫(xiě)法:
import os import os filenames = [filename for filename in os.listdir("Python-Lang/data") if not filename.startswith(".")] #注意,os.listdir返回的是不帶路徑的文件名
讓我們回到copytree()
。用copytree()
來(lái)拷貝目錄時(shí),一個(gè)比較棘手的問(wèn)題是錯(cuò)誤處理。比如在拷貝的過(guò)程中遇到已經(jīng)損壞的符號(hào)鏈接,或者由于權(quán)限問(wèn)題導(dǎo)致有些文件無(wú)法訪問(wèn)等。對(duì)于這種情況,所有遇到的異常會(huì)收集到一個(gè)列表中并將其歸組為一個(gè)單獨(dú)的異常,在操作結(jié)束時(shí)拋出。示例如下:
import shutil src = "Python-Lang/sub_dir" dst = "Python-Lang/sub_dir2" try: shutil.copytree(src, dst) except shutil.Error as e: for src, dst, msg in e.args[0]: print(src, dst, msg)
如果提供了ignore_dangling_symlinks=True
,那么copytree
將會(huì)忽略懸垂的符號(hào)鏈接。
更多關(guān)于shutil
的使用(如記錄日志、文件權(quán)限等)可參見(jiàn)shutil文檔[4]。
接下來(lái)我們看如何使用os.walk()
函數(shù)遍歷層級(jí)目錄以搜索文件。只需要將頂層目錄提供給它即可。比如下列函數(shù)用來(lái)查找一個(gè)特定的文件名,并將所有匹配結(jié)果的絕對(duì)路徑打印出來(lái):
import os def findfile(start, name): for relpath, dirs, files in os.walk(start): if name in files: # print(relpath) full_path = os.path.abspath(os.path.join(relpath, name)) print(full_path) start = "." name = "test.txt" findfile(start, name)
可以看到,os.walk
可為為我們遍歷目錄層級(jí),且對(duì)于進(jìn)入的每個(gè)目錄層級(jí)它都返回一個(gè)三元組,包含:正在檢視的目錄的相對(duì)路徑(相對(duì)腳本執(zhí)行路徑),正在檢視的目錄中包含的所有目錄名列表,正在撿視的目錄中包含的所有文件名列表。這里的os.path.abspath
接受一個(gè)可能是相對(duì)的路徑并將其組成絕對(duì)路徑的形式。
我們還能夠附加地讓腳本完成更復(fù)雜的功能,如下面這個(gè)函數(shù)可打印出所有最近有修改過(guò)的文件:
import os import time def modified_within(start, seconds): now = time.time() for relpath, dirs, files in os.walk(start): for name in files: full_path = os.path.join(relpath, name) mtime = os.path.getmtime(full_path) if mtime > (now - seconds): print(full_path) start = "." seconds = 60 modified_within(start, 60)
3. 創(chuàng)建和解包歸檔文件
如果僅僅是想創(chuàng)建或解包歸檔文件,可以直接使用shutil
模塊中的高層函數(shù):
import shutil shutil.make_archive(base_name="data", format="zip", root_dir="Python-Lang/data") shutil.unpack_archive("data.zip")
其中第二個(gè)參數(shù)format
為期望輸出的格式。要獲取所支持的歸檔格式列表,可以使用get_archive_formats()
函數(shù):
print(shutil.get_archive_formats()) # [('bztar', "bzip2'ed tar-file"), ('gztar', "gzip'ed tar-file"), ('tar', 'uncompressed tar file'), ('xztar', "xz'ed tar-file"), ('zip', 'ZIP file')]
Python也提供了諸如tarfile
、zipfile
、gzip
等模塊來(lái)處理歸檔格式的底層細(xì)節(jié)。比如我們想要?jiǎng)?chuàng)建然后解包.zip
歸檔文件,可以這樣寫(xiě):
import zipfile with zipfile.ZipFile('Python-Lang/data.zip', 'w') as zout: zout.write(filename='Python-Lang/data/test1.txt', arcname="test1.txt") zout.write(filename='Python-Lang/data/test2.txt', arcname="test2.txt") with zipfile.ZipFile('Python-Lang/data.zip', 'r') as zin: zin.extractall('Python-Lang/data2') #沒(méi)有則自動(dòng)創(chuàng)建data2目錄
參考
- [1] https://docs.python.org/3/library/subprocess.html
- [2] https://stackoverflow.com/questions/28708531/what-does-do-in-a-gitignore-file
- [3] https://stackoverflow.com/questions/7099290/how-to-ignore-hidden-files-using-os-listdir
- [4] https://docs.python.org/3/library/shutil.html
- [5] Martelli A, Ravenscroft A, Ascher D. Python cookbook[M]. " O'Reilly Media, Inc.", 2015.
以上就是Python編寫(xiě)實(shí)用運(yùn)維進(jìn)程文件目錄操作腳本示例的詳細(xì)內(nèi)容,更多關(guān)于python運(yùn)維操作腳本的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python獲取服務(wù)器信息的最簡(jiǎn)單實(shí)現(xiàn)方法
這篇文章主要介紹了Python獲取服務(wù)器信息的最簡(jiǎn)單實(shí)現(xiàn)方法,涉及Python中urllib2庫(kù)的使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-03-03Python制作旋轉(zhuǎn)花燈祝大家元宵節(jié)快樂(lè)(實(shí)例代碼)
一年一度的元宵節(jié)來(lái)臨,小編在這里祝大家2022元宵節(jié)快樂(lè),今天小編給大家分享一篇教程關(guān)于Python制作旋轉(zhuǎn)花燈祝大家元宵節(jié)快樂(lè),代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2022-02-02Python+Pygame實(shí)戰(zhàn)之24點(diǎn)游戲的實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了如何利用Python和Pygame實(shí)現(xiàn)24點(diǎn)小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-04-04Python使用xlrd模塊操作Excel數(shù)據(jù)導(dǎo)入的方法
這篇文章主要介紹了Python使用xlrd模塊操作Excel數(shù)據(jù)導(dǎo)入的方法,涉及Python操作xlrd模塊的技巧,需要的朋友可以參考下2015-05-05python實(shí)現(xiàn)Thrift服務(wù)端的方法
這篇文章主要介紹了python實(shí)現(xiàn)Thrift服務(wù)端的方法,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-04-04