首页 > 解决方案 > 如何使用 python 日志记录捕获命令行输出?

问题描述

我正在编写一个脚本来匿名化元数据,并且我正在设置一个日志系统来记录脚本在每次收到主题时是如何执行的。该脚本从在线服务器推送和提取信息,并使用“curl”shell 命令来执行此操作。当我执行脚本时,我在 shell 中得到一个输出,我想将它记录在日志文件中,但我不知道如何捕获它。

目前我将记录器配置为:

import logging

logging.basicConfig(filename='/path/to/logging_test.txt',filemode='a',format='%(asctime)s - %(levelname)s - %(message)s',level=logging.DEBUG)

logger = logging.getLogger(__name__)

然后我在从服务器中提取元数据后执行命令来修改元数据,

os.system(cmd)

哪个输出到 shell 中,如下所示:

{
   "ID" : "dshbjhdoqwdjwebfie",
   "Path" : "/subjects/dshbjhdoqwdjwebfie",
   "Type" : "Subject"
}

我想在日志文本文件中包含它。我该怎么做呢?

标签: pythonshellloggingcommand-linestdout

解决方案


尝试使用os.popen而不是os.system, 将输出作为字符串:

output = os.popen(cmd).read()

然后你可以像任何其他字符串内容一样记录它


推荐阅读