溫馨提示×

python外部命令如何記錄命令執行日志

小樊
136
2024-12-12 01:02:38
欄目: 編程語言

要在Python中記錄外部命令的執行日志,您可以使用subprocess模塊來運行外部命令,并使用logging模塊來記錄輸出和錯誤信息。以下是一個示例代碼:

import subprocess
import logging

# 配置日志記錄
logging.basicConfig(filename='command_execution.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 要執行的外部命令
command = 'echo "Hello, World!"'

# 使用subprocess.run()運行外部命令,并捕獲輸出和錯誤信息
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)

# 記錄命令執行結果
if result.returncode == 0:
    logging.info(f'Command executed successfully: {command}\nOutput: {result.stdout}')
else:
    logging.error(f'Command execution failed: {command}\nError: {result.stderr}')

在這個示例中,我們首先配置了日志記錄,將日志信息寫入名為command_execution.log的文件中。然后,我們使用subprocess.run()函數運行外部命令,并通過設置stdoutstderr參數來捕獲命令的輸出和錯誤信息。最后,我們根據命令的執行結果記錄相應的日志信息。

請注意,使用shell=True可能會導致安全風險,特別是在處理不受信任的輸入時。在這種情況下,建議避免使用shell=True,并通過傳遞命令及其參數作為列表來運行外部命令。例如:

command = ['echo', 'Hello, World!']
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)

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