如何使用 python 日志记录捕获命令行输出?

Lou*_*len 5 python shell logging command-line stdout

我正在编写一个脚本来匿名化元数据,并且正在设置一个日志系统来记录脚本每次收到主题时如何执行。该脚本从在线服务器推送和拉取信息,并使用“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__)
Run Code Online (Sandbox Code Playgroud)

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

os.system(cmd)
Run Code Online (Sandbox Code Playgroud)

其输出到 shell 的内容如下所示:

{
   "ID" : "dshbjhdoqwdjwebfie",
   "Path" : "/subjects/dshbjhdoqwdjwebfie",
   "Type" : "Subject"
}
Run Code Online (Sandbox Code Playgroud)

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

Ada*_*Er8 5

尝试使用os.popen而不是os.system, 来获取字符串输出:

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

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