0

tl;dr how do I pass a logging.Logger instance as a "stream" (similar to sys.stdout) that logs a message for each line of text received?

I'm using the invoke module Runner.run method to run a program /usr/bin/printf. The run method has a parameter out_stream. The docs for Runner.run read:

run(command: str, **kwargs: Any) → Optional[invoke.runners.Result]

Execute command, returning an instance of Result once complete.

out_stream – A file-like stream object to which the subprocess’ standard output should be written. If None (the default), sys.stdout will be used.

The call to run looks like:

import invoke


def print_foobar(context: invoke.context):
    context.run("/usr/bin/printf foobar")

I want to pass a Logger instance as the out_stream like this (pseudo-code):

import invoke
import logging


log = logging.getLogger()

def print_foobar(context: invoke.context):
    context.run("/usr/bin/printf foobar", out_stream=log.stream)

I want the standard out of the child process printf to be logged by Logger instance log. Maybe one log.info message per line of text from the printf child process, or something like that. In other words, how do I get something like a log.stream shown in the prior code snippet?

How can I use the Logger instance as a "file-like stream object" that logs a message for each line of text received?

JamesThomasMoon
  • 6,169
  • 7
  • 37
  • 63
  • Create a class with a `write` method on it, which delegates to `logging.info`. – Peter Wood Aug 26 '23 at 00:41
  • This is definitely a duplicate; what I have there is the best I can find at the moment but it should be possible to find better. But yes, it's exactly as @PeterWood says. If that isn't enough of a hint, you'll need to ask a more specific question, after making an attempt. You may also find https://stackoverflow.com/questions/6657820 insightful, although this is meant more for *input* streams. – Karl Knechtel Aug 26 '23 at 01:54
  • "_This is definitely a duplicate_" This question not a duplicate of [Creating a stream class in Python](https://stackoverflow.com/questions/5558622/creating-a-stream-class-in-python). This question also asks about a line-oriented mechanism for the passed `Logger` instance. Secondly, Peter Wood's hint "_Create a class with a write method on it_" has no necessary relationship with the other questions' Answer of using the `io` module. "_you'll need to ask a more specific question_" this **is** a very specific question. – JamesThomasMoon Aug 26 '23 at 01:59
  • 2
    There's a recipe here: https://docs.python.org/3/howto/logging-cookbook.html#how-to-treat-a-logger-like-an-output-stream – Peter Wood Aug 26 '23 at 20:32
  • @JamesThomasMoon look at Peter Wood's *other* comment, which links to a recipe in the Python logging documentation (the logging cookbook). – Vinay Sajip Aug 30 '23 at 02:40

0 Answers0