要在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()
函數運行外部命令,并通過設置stdout
和stderr
參數來捕獲命令的輸出和錯誤信息。最后,我們根據命令的執行結果記錄相應的日志信息。
請注意,使用shell=True
可能會導致安全風險,特別是在處理不受信任的輸入時。在這種情況下,建議避免使用shell=True
,并通過傳遞命令及其參數作為列表來運行外部命令。例如:
command = ['echo', 'Hello, World!']
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)