Nocturn9X
Nocturn9X

Reputation: 45

Capture logging output using subprocess.check_output in Python

I'm running a Telegram bot which is basically an interface to a Bayesian classifier that I made. I made a command to start a test on the remote server and the tester was originally using the logging module to print information about the test to stdout. When I tried to spawn a subprocess through subprocess.check_output I noticed that both stdout and stderr where empty byte strings. I worked around this by replacing the last logging.info call, the one that really matters, with a print function. What I'm guessing is that logging does not write on the same stdout that subprocess.check_output is expecting? Am I doing something wrong?

EDIT

As asked I'm adding a bit more context about what code I'm actually running. I don't know if this matters, but for the sake of completeness I'll add that the framework I'm using to run the bot is pyrogram.

The tester that gets called by the bot can be found here, while the code of the bot calling that script is here

Upvotes: 1

Views: 1152

Answers (1)

AgileZebra
AgileZebra

Reputation: 583

I'm guessing is that logging does not write on the same stdout that subprocess.check_output is expecting?

logging doesn't write to stdout at all (by default); it writes to stderr.

You will need to either redirect your stderr to stdout by adding the stderr argument thus: subprocess.check_output(..., stderr=subprocess.STDOUT) or you will need to use one of the other subprocess functions such as run that gives access to stderr.

The docs do say:

The recommended approach to invoking subprocesses is to use the run() function for all use cases it can handle

Upvotes: 1

Related Questions