溫馨提示×

python外部命令如何進行錯誤處理

小樊
100
2024-12-12 01:45:38
欄目: 編程語言

在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=Truecapture_output=True以便以文本形式捕獲命令的輸出。

如果命令執行成功,我們將輸出結果打印到控制臺。如果命令執行失敗,我們將捕獲subprocess.CalledProcessError異常,并打印錯誤信息和命令的輸出(如果有)。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女