pythonabstract-syntax-treerope

convert python print statements to logging


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.


Solution

  • 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 .