利用Python編寫的實用運(yùn)維腳本分享
Python在很大程度上可以對shell腳本進(jìn)行替代。筆者一般單行命令用shell,復(fù)雜點的多行操作就直接用Python了。這篇文章就歸納一下Python的一些實用腳本操作。
1. 執(zhí)行外部程序或命令
我們有以下C語言程序cal.c(已編譯為.out文件),該程序負(fù)責(zé)輸入兩個命令行參數(shù)并打印它們的和。該程序需要用Python去調(diào)用C語言程序并檢查程序是否正常返回(正常返回會返回 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ù)來spawn一個子進(jìn)程:
res = subprocess.run(["Python-Lang/cal.out", "1", "2"]) print(res.returncode)
可以看到控制臺打印出進(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)
不過我們在程序運(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
可以看到控制臺打印輸出的進(jìn)程返回值為-15(因為負(fù)值-N表示子進(jìn)程被信號N終止,而kill命令默認(rèn)的信號是15,該信號會終止進(jìn)程):
-15
如果程序陷入死循環(huán)不能正常終止,我們總不能一直等著吧?此時,我們可以設(shè)置超時機(jī)制并進(jìn)行異常捕捉:
try: res = subprocess.run(["Python-Lang/while.out"], capture_output=True, timeout=5) except subprocess.TimeoutExpired as e: print(e)
此時會打印輸出異常結(jié)果:
Command '['Python-Lang/while.out']' timed out after 5 seconds
有時需要獲取程序的輸出結(jié)果,此時可以加上capture_output
參數(shù),然后訪問返回對象的stdout
屬性即可:
res = subprocess.run(["netstat", "-a"], capture_output=True) out_bytes = res.stdout
輸出結(jié)果是以字節(jié)串返回的,如果想以文本形式解讀,可以再增加一個解碼步驟:
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 %
一般來說,命令的執(zhí)行不需要依賴底層shell的支持(如sh,bash等),我們提供的字符串列表會直接傳遞給底層的系統(tǒng)調(diào)用,如os.execve()
。如果希望命令通過shell來執(zhí)行,只需要給定參數(shù)shell=True
并將命令以簡單的字符串形式提供即可。比如我們想讓Python執(zhí)行一個涉及管道、I/O重定向或其它復(fù)雜的Shell命令時,我們就可以這樣寫:
out_bytes = subprocess.run("ps -a|wc -l> out", shell=True)
2. 文件和目錄操作(命名、刪除、拷貝、移動等)
我們想要和文件名稱和路徑打交道時,為了保證獲得最佳的移植性(尤其是需要同時運(yùn)行與Unix和Windows上時),最好使用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
未知時, 將不做任何操作。如我們這里的$HOME
就為/Users/orion-orion
:
(base) orion-orion@MacBook-Pro ~ % echo $HOME /Users/orion-orion
如果要刪除文件,請用os.remove
(在刪除前注意先判斷文件是否存在):
file_name = "Python-Lang/test.txt" if os.path.exists(file_name): os.remove(file_name)
接下來我們看如何拷貝文件。當(dāng)然最直接的方法是調(diào)用Shell命令:
os.system("cp Python-Lang/test.txt Python-Lang/test2.txt")
當(dāng)然這不夠優(yōu)雅。如果不像通過調(diào)用shell命令來實現(xiàn),可以使用shutil模塊,該模塊提供了一系列對文件和文件集合的高階操作,其中就包括文件拷貝和移動/重命名。這些函數(shù)的參數(shù)都是字符串,用來提供文件或目錄的名稱。以下是示例:
src = "Python-Lang/test.txt" dst = "Python-Lang/test2.txt" # 對應(yīng)cp src dst (拷貝文件,存在則覆蓋) shutil.copy(src, dst) src = "Python-Lang/sub_dir" dst = "Python-Lang/sub_dir2" # 對應(yīng)cp -R src dst (拷貝整個目錄樹) shutil.copytree(src, dst) src = "Python-Lang/test.txt" dst = "Python-Lang/sub_dir/test2.txt" # 對應(yīng)mv src dst (移動文件,可選擇是否重命名) shutil.move(src, dst)
可以看到,正如注釋所言,這些函數(shù)的語義和Unix命令類似。如果你對Unix下的文件拷貝/移動等操作不熟悉,可以參見Linux shell進(jìn)行文件解壓,復(fù)制和移動詳解
默認(rèn)情況下,如果源文件是一個符號鏈接,那么目標(biāo)文件將會是該鏈接所指向的文件的拷貝。如果只想拷貝符號鏈接本身,可以提供關(guān)鍵字參數(shù)follow_symlinks:
shutil.copy(src, dst, follow_symlinks=True)
如果想在拷貝的目錄中保留符號鏈接,可以這么做:
shutil.copytree(src, dst, symlinks=True)
有時在拷貝整個目錄時需要對特定的文件和目錄進(jìn)行忽略,如.pyc
這種中間過程字節(jié)碼。我們可以為copytree
提供一個ignore函數(shù),該函數(shù)已目錄名和文件名做為輸入?yún)?shù),返回一列要忽略的名稱做為結(jié)果(此處用到字符串對象的.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)
不過由于忽略文件名這種模式非常常見,已經(jīng)有一個實用函數(shù)ignore_patterns()
提供給我們使用了(相關(guān)模式使用方法類似.gitignore
):
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("*~", "*.pyc"))
注:此處的"*~"
模式匹配是文本編輯器(如Vi)產(chǎn)生的以"~"結(jié)尾的中間文件。
忽略文件名還常常用在os.listdir()
中。比如我們在數(shù)據(jù)密集型(如機(jī)器學(xué)習(xí))應(yīng)用中,需要遍歷data
目錄下的所有數(shù)據(jù)集文件并加載,但是需要排除.
開頭的隱藏文件,如.git
,否則會出錯,此時可采用下列寫法:
import os import os filenames = [filename for filename in os.listdir("Python-Lang/data") if not filename.startswith(".")] #注意,os.listdir返回的是不帶路徑的文件名
讓我們回到copytree()
。用copytree()
來拷貝目錄時,一個比較棘手的問題是錯誤處理。比如在拷貝的過程中遇到已經(jīng)損壞的符號鏈接,或者由于權(quán)限問題導(dǎo)致有些文件無法訪問等。對于這種情況,所有遇到的異常會收集到一個列表中并將其歸組為一個單獨的異常,在操作結(jié)束時拋出。示例如下:
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
將會忽略懸垂的符號鏈接。
更多關(guān)于shutil
的使用(如記錄日志、文件權(quán)限等)可參見shutil文檔[4]。
接下來我們看如何使用os.walk()
函數(shù)遍歷層級目錄以搜索文件。只需要將頂層目錄提供給它即可。比如下列函數(shù)用來查找一個特定的文件名,并將所有匹配結(jié)果的絕對路徑打印出來:
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ìn)入的每個目錄層級它都返回一個三元組,包含:正在檢視的目錄的相對路徑(相對腳本執(zhí)行路徑),正在檢視的目錄中包含的所有目錄名列表,正在撿視的目錄中包含的所有文件名列表。這里的os.path.abspath
接受一個可能是相對的路徑并將其組成絕對路徑的形式。
我們還能夠附加地讓腳本完成更復(fù)雜的功能,如下面這個函數(shù)可打印出所有最近有修改過的文件:
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")
其中第二個參數(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
等模塊來處理歸檔格式的底層細(xì)節(jié)。比如我們想要創(chuàng)建然后解包.zip
歸檔文件,可以這樣寫:
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') #沒有則自動創(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
到此這篇關(guān)于利用Python編寫的實用運(yùn)維腳本分享的文章就介紹到這了,更多相關(guān)Python運(yùn)維腳本內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Python實現(xiàn)B站視頻數(shù)據(jù)信息內(nèi)容采集
這篇文章主要介紹了如何基于Python實現(xiàn)B站視頻數(shù)據(jù)信息內(nèi)容采集,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)python的小伙伴們有非常好的幫助,需要的朋友可以參考下2024-02-02python讀取txt文件并取其某一列數(shù)據(jù)的示例
今天小編就為大家分享一篇python讀取txt文件并取其某一列數(shù)據(jù)的示例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02Python配置文件管理之ini和yaml文件讀取的實現(xiàn)
本文主要介紹了Python配置文件管理之ini和yaml文件讀取,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02