在Python中,可以使用subprocess
模塊來執行外部命令
import subprocess
def run_command(command):
try:
# 使用列表形式執行命令,避免shell注入風險
result = subprocess.run(command, check=True, text=True, capture_output=True)
print("Command output:", result.stdout)
except subprocess.CalledProcessError as e:
print("Error occurred while running the command:", e)
print("Command output (stderr):", e.stderr)
command = ["ls", "-l"]
run_command(command)
在這個示例中,我們定義了一個名為run_command
的函數,它接受一個命令列表作為參數。我們使用subprocess.run()
函數來執行命令,并設置check=True
以便在命令返回非零退出狀態時引發subprocess.CalledProcessError
異常。我們還設置了text=True
和capture_output=True
以便以文本形式捕獲命令的輸出。
如果命令執行成功,我們將輸出結果打印到控制臺。如果命令執行失敗,我們將捕獲subprocess.CalledProcessError
異常,并打印錯誤信息和命令的輸出(如果有)。