Pregunta

I'm working on a large codebase that uses print statements for logging rather than python logging. I'm wondering if there is a recommended for converting all these print statements to calls to logging.info? Many of these prints are spread over several lines and thus any solution needs to handle those cases and hopefully would maintain formatting.

I've looked into python rope but that doesn't seem to have the facility to convert calls to statement like print to a function call.

¿Fue útil?

Solución

You could use 2to3 and only apply the fix for print statement -> print function.

2to3 --fix=print [yourfiles]          # just displays the diff on stdout
2to3 --fix=print [yourfiles] --write  # also saves the changes to disk

This should automatically handle all those strange cases, and then converting print functions to logging functions should be a straightforward find-and-replace with, e.g., sed.

If you don't have the shortcut for the 2to3 script for some reason, run lib2to3 as a module instead:

python -m lib2to3 --fix=print .

Otros consejos

just add this few line before your code starts and it will log everything it prints. I think you are looking for something like this.

import logging
import sys

class writer :
    def __init__(self, *writers) :
        self.writers = writers

    def write(self, text) :
        logging.warning(text)


saved = sys.stdout
sys.stdout = writer(sys.stdout)


print "There you go."
print "There you go2."
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top