Louise Cullen
Louise Cullen

Reputation: 107

How to capture command-line output with python logging?

I am writing a script to anonymize metadata, and I am setting up a logging system to record how the script is carried out each time it receives a subject. The script pushes and pulls information from an online server, and uses a "curl" shell commands to do so. When I execute the script, I get an output in the shell that I would like to be recorded in the log file, but I don't know how to capture it.

At the moment I have the logger configured as:

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__)

Then I execute the command to modify the metadata once I've pulled it from the server,

os.system(cmd)

Which outputs into the shell something like the following:

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

Which I would like to have in the log textfile. How do I do this?

Upvotes: 5

Views: 10742

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13403

try using os.popen instead of os.system, to get the output as a string:

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

then you can log it like any other string content

Upvotes: 5

Related Questions