在Python中,可以使用subprocess模塊來執行CMD命令并處理錯誤
import subprocess
def run_cmd_command(command):
try:
# 執行CMD命令
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
# 打印命令輸出
print("Command output:", result.stdout)
except subprocess.CalledProcessError as e:
# 捕獲命令錯誤
print("Error occurred while running the command:", e)
print("Error output:", e.stderr)
if __name__ == "__main__":
cmd_command = "your_cmd_command_here" # 請替換為你要執行的CMD命令
run_cmd_command(cmd_command)
在這個示例中,我們定義了一個名為run_cmd_command的函數,它接受一個CMD命令作為參數。我們使用subprocess.run()函數來執行命令,并將stdout和stderr參數設置為subprocess.PIPE以便捕獲命令輸出。text參數設置為True以便以文本模式處理輸出。check參數設置為True以便在命令返回非零退出狀態時引發subprocess.CalledProcessError異常。
在try塊中,我們執行命令并打印輸出。在except塊中,我們捕獲subprocess.CalledProcessError異常并打印錯誤信息。