Python?運行?shell?命令的方法匯總
我們知道,python 在自動化領域中被廣泛應用,可以很好地自動化處理一些任務
就比如編寫 Python 腳本自動化執(zhí)行重復性的任務,如文件處理、數(shù)據(jù)處理、系統(tǒng)管理等需要運行其他程序或者與操作系統(tǒng)交互的任務
那么今天我們來看一下在 python 中如何運行 shell 命令來與操作系統(tǒng)交互
一般來講,最好是用 python 自帶的函數(shù)或模塊,而不是直接調(diào)用其他程序或者操作系統(tǒng)的命令
我們來看一下 python 中有哪些自帶模塊或者方法可以實現(xiàn)
pathlib
模塊
如果你需要創(chuàng)建或者刪除文件/目錄,檢查文件是否存在或者改變權限等,你完全不需要使用操作系統(tǒng)的命令
你可以完全通過 pathlib
模塊來實現(xiàn),它有你需要的一切,甚至 glob
、os.path
都可以不用
我們來簡單看一下關于這個模塊的例子
from pathlib import Path # 創(chuàng)建一個Path對象表示當前工作目錄 current_directory = Path.cwd() print("當前工作目錄:", current_directory) # 創(chuàng)建一個新的目錄 new_directory = current_directory / "my_folder" new_directory.mkdir() print("創(chuàng)建新目錄:", new_directory) # 創(chuàng)建一個新的文件 new_file = new_directory / "my_file.txt" new_file.touch() print("創(chuàng)建新文件:", new_file) # 寫入文件 with new_file.open(mode='w') as f: f.write("Hello, World!") # 讀取文件內(nèi)容 with new_file.open() as f: content = f.read() print("文件內(nèi)容:", content) # 遍歷目錄中的文件 for file in new_directory.iterdir(): print("文件:", file) # 刪除文件和目錄 new_file.unlink() new_directory.rmdir() print("刪除文件和目錄:", new_file, new_directory)
tempfile
模塊
在 Python 中臨時創(chuàng)建和處理文件時,tempfile
模塊提供了方便的方法
它可以在臨時目錄中創(chuàng)建臨時文件和臨時文件夾,并提供了一些便利的函數(shù)和類來管理這些臨時文件
import tempfile # 創(chuàng)建臨時文件 temp_file = tempfile.NamedTemporaryFile(delete=False) temp_file.write(b'This is a temporary file.') temp_file.close() # 打印臨時文件路徑 print("臨時文件路徑:", temp_file.name) # 打開臨時文件并讀取內(nèi)容 with open(temp_file.name, 'r') as f: content = f.read() print("臨時文件內(nèi)容:", content) # 創(chuàng)建臨時目錄 temp_dir = tempfile.TemporaryDirectory() # 打印臨時目錄路徑 print("臨時目錄路徑:", temp_dir.name) # 自動清理臨時目錄 temp_dir.cleanup()
shutil
模塊
前面我們知道 pathlib
模塊滿足了 python 中大多數(shù)與文件相關的需求
如果需要例如復制,移動,刪除或創(chuàng)建文件,可以使用 shutil
模塊
import shutil # 復制文件 shutil.copy('source_file.txt', 'destination_folder/') # 移動文件 shutil.move('source_file.txt', 'destination_folder/') # 刪除文件 shutil.remove('file_to_be_deleted.txt') # 刪除目錄 shutil.rmtree('directory_to_be_deleted/') # 創(chuàng)建壓縮文件 shutil.make_archive('archive', 'zip', 'source_folder/') # 解壓縮文件 shutil.unpack_archive('archive.zip', 'destination_folder/')
os
模塊
os
模塊是 Python 中一個更老的、更底層的模塊,提供了與操作系統(tǒng)交互和執(zhí)行文件系統(tǒng)操作的功能
但是隨著 python 的發(fā)展,越來越多面向?qū)ο蟮摹⒏庇^和易于使用的模塊可以供大家使用
對于 os
模塊,大家可以了解一下就行了
import os print(os.getenv('PATH')) # 獲取環(huán)境變量PATH的值,并打印 # 示例輸出:/home/martin/.local/bin:/usr/local/sbin:/usr/local/bin:... print(os.uname()) # 獲取操作系統(tǒng)的信息,并打印 # 示例輸出:posix.uname_result(sysname='Linux', nodename='...', release='...', version='...', machine='x86_64') print(os.times()) # 獲取進程的CPU時間信息,并打印 # 示例輸出:posix.times_result(user=0.01, system=0.0, children_user=0.0, children_system=0.0, elapsed=1740.63) print(os.cpu_count()) # 獲取可用的CPU核心數(shù)量,并打印 # 示例輸出:16 print(os.getloadavg()) # 獲取系統(tǒng)的平均負載,并打印 # 示例輸出:(2.021484375, 2.35595703125, 2.04052734375) old_umask = os.umask(0o022) # 設置文件創(chuàng)建時的權限掩碼,并將舊的掩碼保存起來 # 在此處可以執(zhí)行與文件相關的操作... os.umask(old_umask) # 恢復舊的文件權限掩碼
sh
模塊
sh
模塊不是 python 的標準模塊,它是一個第三方模塊,在使用之前我們需要安裝它
pip install sh
import sh # 在 $PATH 中運行任何命令... print(sh.ls('-la')) # 執(zhí)行l(wèi)s命令并打印輸出 # 示例輸出: # total 36 # drwxrwxr-x 2 martin martin 4096 apr 8 14:18 . # drwxrwxr-x 41 martin martin 20480 apr 7 15:23 .. # -rw-rw-r-- 1 martin martin 30 apr 8 14:18 examples.py ls_cmd = sh.Command('ls') print(ls_cmd('-la')) # 顯式調(diào)用 # 使用Command對象執(zhí)行l(wèi)s命令并打印輸出 # 示例輸出與上述相同 # 如果命令不在PATH中: custom_cmd = sh.Command('/path/to/my/cmd') custom_cmd('some', 'args') # 執(zhí)行自定義命令并傳遞參數(shù) with sh.contrib.sudo: # 使用'sudo'執(zhí)行一些操作... ... # 使用'sudo'執(zhí)行一些操作的上下文環(huán)境
當我們通過 sh
模塊去執(zhí)行一些 shell 命令時,sh 模塊會嘗試在本地環(huán)境變量($PATH)中查找?guī)в性撁Q的內(nèi)置 shell 命令或二進制文件
如果沒有找到,可以自己添加命令路徑
custom_cmd = sh.Command('/path/to/my/cmd') custom_cmd('some', 'args') # 執(zhí)行自定義命令并傳遞參數(shù)
如果要將命令的輸出寫入到文件里面,可以使用 _out
參數(shù)
#相當于 ip address > /tmp/ipaddr sh.ip.address(_out='/tmp/ipaddr')
我們在敲 shell 命令時通常會使用到管道符(|),在 sh 模塊中通過 _in
參數(shù)來實現(xiàn)
print(sh.awk('{print $9}', _in=sh.ls('-la'))) # 等同于 "ls -la | awk '{print $9}'" print(sh.wc('-l', _in=sh.ls('.', '-1'))) # 等同于 "ls -1 | wc -l"
對于異常處理,我們可以簡單地處理 ErrorReturnCode
或 TimeoutException
異常
try: sh.cat('/tmp/doesnt/exist') except sh.ErrorReturnCode as e: print(f'Command {e.full_cmd} exited with {e.exit_code}') # '/usr/bin/cat /tmp/doesnt/exist' 命令結果返回 1 curl = sh.curl('https://httpbin.org/delay/5', _bg=True) try: curl.wait(timeout=3) except sh.TimeoutException: print("Command timed out...") curl.kill()
到此這篇關于Python 運行 shell 命令的一些方法的文章就介紹到這了,更多相關Python 運行 shell 命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python基于xml parse實現(xiàn)解析cdatasection數(shù)據(jù)
這篇文章主要介紹了python基于xml parse實現(xiàn)解析cdatasection數(shù)據(jù)的方法,是非常實用技巧,需要的朋友可以參考下2014-09-09基于python實現(xiàn)鼠標實時坐標監(jiān)測
這篇文章主要給大家介紹了如何基于python實現(xiàn)鼠標實時坐標監(jiān)測,文章通過代碼示例介紹的非常詳細,對大家的學習或工作有一定的幫助,需要的朋友可以參考下2023-11-11Python 微信之獲取好友昵稱并制作wordcloud的實例
今天小編就為大家分享一篇Python 微信之獲取好友昵稱并制作wordcloud的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02關于生產(chǎn)消費者模型中task_done()的具體作用
這篇文章主要介紹了關于生產(chǎn)消費者模型中task_done()的具體作用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02