python run shell命令示例
使用subprocess.run() 可安全執行shell 命令並捕獲輸出,推薦以列表傳參避免注入風險;2. 需要shell 特性時可設shell=True,但需警惕命令注入;3. 使用subprocess.Popen 可實現實時輸出處理;4. 設置check=True 可在命令失敗時拋出異常;5. 簡單場景可直接鍊式調用獲取輸出;日常應優先使用subprocess.run(),避免使用os.system() 或已棄用模塊,以上方法覆蓋了Python 中執行shell 命令的核心用法。
在Python 中執行shell 命令有多種方式,最常用的是使用subprocess
模塊。下面是一些實用的例子,展示如何在Python 中運行shell 命令。

1. 使用subprocess.run()
(推薦方式)
這是Python 3.5 推薦的方法,簡單、安全且功能強大。
import subprocess # 運行一個簡單的shell 命令result = subprocess.run(['ls', '-l'], capture_output=True, text=True) # 輸出命令的返回碼、標準輸出和錯誤print("返回碼:", result.returncode) print("輸出:\n", result.stdout) print("錯誤:\n", result.stderr)
? 注意:
['ls', '-l']
是以列表形式傳參,避免shell 注入風險。如果需要shell 特性(如通配符、管道),加shell=True
。
2. 運行帶shell 特性的命令(使用shell=True
)
import subprocess result = subprocess.run('echo $HOME | xargs ls', shell=True, capture_output=True, text=True) print("輸出:\n", result.stdout)
⚠️ 警告:使用shell=True
時要小心用戶輸入,防止命令注入。
3. 實時輸出命令執行過程(不等待完成)
如果你希望看到命令實時輸出(比如長時間運行的腳本):

import subprocess # 實時打印輸出process = subprocess.Popen(['ping', '-c', '5', 'google.com'], stdout=subprocess.PIPE, text=True) for line in process.stdout: print("輸出:", line.strip()) process.wait() # 等待完成print("完成,返回碼:", process.returncode)
4. 執行命令並獲取返回值判斷是否成功
import subprocess try: subprocess.run(['python', '--version'], check=True, capture_output=True, text=True) print("命令執行成功") except subprocess.CalledProcessError as e: print("命令執行失敗:", e)
-
check=True
會在命令返回非零狀態時拋出異常。
5. 快速執行並獲取輸出(適合簡單場景)
如果你只是想快速獲取命令輸出,可以用:
import subprocess # 簡潔寫法output = subprocess.run('date', shell=True, capture_output=True, text=True).stdout.strip() print("當前時間:", output)
常見用途示例
檢查文件是否存在:
result = subprocess.run(['test', '-f', 'config.txt'], capture_output=True) if result.returncode == 0: print("文件存在")
執行Git 命令:
result = subprocess.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], capture_output=True, text=True) print("當前分支:", result.stdout.strip())
基本上就這些常用方式。日常推薦優先使用
subprocess.run()
,避免使用已棄用的os.system()
或commands
模塊。以上是python run shell命令示例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

runthewindowsupdatetrubloubleshooterviaSettings>更新&安全> is esseShootsoAtomationfixCommonissues.2.ResetWindowSupDateComponentsByStoppingRealatedServices,RenamingTheSoftWaredWaredWaredSoftwaredSistribution andCatroot2Folders,intrestrestartingthertingthertingtherserviceSteStoceTocle

ahashmapinjavaiSadattrastureturethatStoreskey-valuepairsforefficeFitedReval,插入和deletion.itusesthekey’shashcode()methodtodeTermInestorageLageLageAgeLageAgeAgeAgeAgeAneStorageAgeAndAllowSavereo(1)timecomplexityforget()

toCreateAnduseanArrayInjava,第一declethearraywithththetatepeandsquarebarackets,thanStantiateItWithTheneWkeyWordeRinitialIseIsizitDirectlywithvalues; 1.DecleAteAteAndeAnArrayUsishArayusisherusingDataType [] ArraynAmeDatepe [] arraynAmename = newDatatepe [size]

YouCancReateathReadInjavaByExtDingTheThEthEthEthReadClassOrimplementingTherunnablefface.2.ExtDendingThreadThreadInvolvesCreatingingAclassThatoverRidestherun()MethodAndCallingStart()onaninstance.3.implementingrementingRunnnablerequirequirequirequirequiresdefinterun()

在使用argparse模塊時,必須提供的參數可通過設置required=True來實現,1.使用required=True可將可選參數(如--input)設為必填,運行腳本時若未提供會報錯;2.位置參數默認必填,無需設置required=True;3.建議必要參數使用位置參數,偶爾必須的配置再使用required=True的可選參數,以保持靈活性;4.required=True是控制參數必填最直接的方式,使用後用戶調用腳本時必須提供對應參數,否則程序將提示錯誤並退出。

選擇:linkedhashsetForinsertionorder,andreesetForsortedOrder.2.addelementswithadd()andremoveWithRemove()

在SpringBoot中,處理請求參數的方法包括:1.使用@RequestParam獲取查詢參數,支持必填、可选和默認值;2.通過List或Map類型接收多個同名參數;3.結合@ModelAttribute將多個參數綁定到對象;4.使用@PathVariable提取URL路徑中的變量;5.在POST請求中用@RequestParam處理表單數據;6.用Map接收所有請求參數。正確選擇註解可高效解析請求數據,提升開發效率。
