Python在很大程度上可以對shell腳本進行替代,筆者一般單行命令用shell,復雜點的多行操作就直接用Python了,這篇文章就歸納一下Python的一些實用腳本操作,
1. 執行外部程式或命令
我們有以下C語言程式cal.c(已編譯為.out檔案),該程式負責輸入兩個命令列引數并列印它們的和,該程式需要用Python去呼叫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函式來spawn一個子行程:
res = subprocess.run(["Python-Lang/cal.out", "1", "2"])
print(res.returncode)
可以看到控制臺列印出行程的回傳值0:
1 + 2 = 3
0
當然,如果程式中途被殺死,如我們將下列while.c程式寫為下列死回圈(已編譯為.out檔案):
#include<stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[]){
while(1);
return 0;
}
我們同樣用run函式接收其回傳值:
res = subprocess.run("Python-Lang/while.out")
print(res.returncode)
不過我們在程式運行中用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
可以看到控制臺列印輸出的行程回傳值為-15(因為負值-N表示子行程被信號N終止,而kill命令默認的信號是15,該信號會終止行程):
-15
如果程式陷入死回圈不能正常終止,我們總不能一直等著吧?此時,我們可以設定超時機制并進行例外捕捉:
try:
res = subprocess.run(["Python-Lang/while.out"], capture_output=True, timeout=5)
except subprocess.TimeoutExpired as e:
print(e)
此時會列印輸出例外結果:
Command '['Python-Lang/while.out']' timed out after 5 seconds
有時需要獲取程式的輸出結果,此時可以加上capture_output引數,然后訪問回傳物件的stdout屬性即可:
res = subprocess.run(["netstat", "-a"], capture_output=True)
out_bytes = res.stdout
輸出結果是以位元組串回傳的,如果想以文本形式解讀,可以再增加一個解碼步驟:
out_text = out_bytes.decode("utf-8")
print(out_text)
可以看到已正常獲取文本形式的輸出結果:
...
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 %
一般來說,命令的執行不需要依賴底層shell的支持(如sh,bash等),我們提供的字串串列會直接傳遞給底層的系統呼叫,如os.execve(),如果希望命令通過shell來執行,只需要給定引數shell=True并將命令以簡單的字串形式提供即可,比如我們想讓Python執行一個涉及管道、I/O重定向或其它復雜的Shell命令時,我們就可以這樣寫:
out_bytes = subprocess.run("ps -a|wc -l> out", shell=True)
2. 檔案和目錄操作(命名、洗掉、拷貝、移動等)
我們想要和檔案名稱和路徑打交道時,為了保證獲得最佳的移植性(尤其是需要同時運行與Unix和Windows上時),最好使用os.path中的函式,例如:
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當用戶或$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)
接下來我們看如何拷貝檔案,當然最直接的方法是呼叫Shell命令:
os.system("cp Python-Lang/test.txt Python-Lang/test2.txt")
當然這不夠優雅,如果不像通過呼叫shell命令來實作,可以使用shutil模塊,該模塊提供了一系列對檔案和檔案集合的高階操作,其中就包括檔案拷貝和移動/重命名,這些函式的引數都是字串,用來提供檔案或目錄的名稱,以下是示例:
src = "https://www.cnblogs.com/orion-orion/archive/2022/05/12/Python-Lang/test.txt"
dst = "Python-Lang/test2.txt"
# 對應cp src dst (拷貝檔案,存在則覆寫)
shutil.copy(src, dst)
src = "https://www.cnblogs.com/orion-orion/archive/2022/05/12/Python-Lang/sub_dir"
dst = "Python-Lang/sub_dir2"
# 對應cp -R src dst (拷貝整個目錄樹)
shutil.copytree(src, dst)
src = "https://www.cnblogs.com/orion-orion/archive/2022/05/12/Python-Lang/test.txt"
dst = "Python-Lang/sub_dir/test2.txt"
# 對應mv src dst (移動檔案,可選擇是否重命名)
shutil.move(src, dst)
可以看到,正如注釋所言,這些函式的語意和Unix命令類似,如果你對Unix下的檔案拷貝/移動等操作不熟悉,可以參見我的博客《Linux:檔案解壓、復制和移動的若干坑》,
默認情況下,如果源檔案是一個符號鏈接,那么目標檔案將會是該鏈接所指向的檔案的拷貝,如果只想拷貝符號鏈接本身,可以提供關鍵字引數follow_symlinks:
shutil.copy(src, dst, follow_symlinks=True)
如果想在拷貝的目錄中保留符號鏈接,可以這么做:
shutil.copytree(src, dst, symlinks=True)
有時在拷貝整個目錄時需要對特定的檔案和目錄進行忽略,如.pyc這種中間程序位元組碼,我們可以為copytree提供一個ignore函式,該函式已目錄名和檔案名做為輸入引數,回傳一列要忽略的名稱做為結果(此處用到字串物件的.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)
不過由于忽略檔案名這種模式非常常見,已經有一個實用函式ignore_patterns()提供給我們使用了(相關模式使用方法類似.gitignore):
shutil.copytree(src, dst, ignore=shutil.ignore_patterns("*~", "*.pyc"))
注:此處的"*~"模式匹配是文本編輯器(如Vi)產生的以"~"結尾的中間檔案,
忽略檔案名還常常用在os.listdir()中,比如我們在資料密集型(如機器學習)應用中,需要遍歷data目錄下的所有資料集檔案并加載,但是需要排除.開頭的隱藏檔案,如.git,否則會出錯,此時可采用下列寫法:
import os
import os
filenames = [filename for filename in os.listdir("Python-Lang/data") if not filename.startswith(".")] #注意,os.listdir回傳的是不帶路徑的檔案名
讓我們回到copytree(),用copytree()來拷貝目錄時,一個比較棘手的問題是錯誤處理,比如在拷貝的程序中遇到已經損壞的符號鏈接,或者由于權限問題導致有些檔案無法訪問等,對于這種情況,所有遇到的例外會收集到一個串列中并將其歸組為一個單獨的例外,在操作結束時拋出,示例如下:
import shutil
src = "https://www.cnblogs.com/orion-orion/archive/2022/05/12/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將會忽略懸垂的符號鏈接,
更多關于shutil的使用(如記錄日志、檔案權限等)可參見shutil檔案[4],
接下來我們看如何使用os.walk()函式遍歷層級目錄以搜索檔案,只需要將頂層目錄提供給它即可,比如下列函式用來查找一個特定的檔案名,并將所有匹配結果的絕對路徑列印出來:
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可為為我們遍歷目錄層級,且對于進入的每個目錄層級它都回傳一個三元組,包含:正在檢視的目錄的相對路徑(相對腳本執行路徑),正在檢視的目錄中包含的所有目錄名串列,正在撿視的目錄中包含的所有檔案名串列,這里的os.path.abspath接受一個可能是相對的路徑并將其組成絕對路徑的形式,
我們還能夠附加地讓腳本完成更復雜的功能,如下面這個函式可列印出所有最近有修改過的檔案:
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. 創建和解包歸檔檔案
如果僅僅是想創建或解包歸檔檔案,可以直接使用shutil模塊中的高層函式:
import shutil
shutil.make_archive(base_name="data", format="zip", root_dir="Python-Lang/data")
shutil.unpack_archive("data.zip")
其中第二個引數format為期望輸出的格式,要獲取所支持的歸檔格式串列,可以使用get_archive_formats()函式:
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等模塊來處理歸檔格式的底層細節,比如我們想要創建然后解包.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') #沒有則自動創建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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/472915.html
標籤:其他
