Convert commented out print statements to logging calls - Python
Question: I'm hacking on a framwork right now, and I'd like to use logging. However, the
developers of the framework have been using print statements to debug, and
they are all commented out for the production release. I was wondering, does
anyone know of a regex to find these, and convert them to logging calls.

This is what I was thinking so far:

    
    
    import re
    import sys
    import StringIO
    
    if not len(sys.argv) != 2:
        print 'Syntax: printtologging.py file_to_process'
    
    regex = r'#print (?P<debugstring>*)$'
    
    output = StringIO.StringIO('w+')
    
    def replace(match_object):
        return 'logging.debug({0})'.format(match_object.group_dict['debugstring'])
    
    with open(sys.argv[1]) as f:
        output.writelines([re.sub(regex, replace, line) for line in f.readlines()])
    
    output.seek(0)
    print output.read()
    

Though that dosn't seem to be working. My regex's are far from brilliant,
could anyone help?


Answer: If you want to do it in Python, consider using the
[fileinput](http://docs.python.org/library/fileinput.html#module-fileinput)
module:

    
    
    import fileinput
    import sys
    import re
    
    def convert(paths):
        for line in fileinput.input(paths, inplace=True, backup='~'):
            line=re.sub(r'#\s*print\s*(.*)',r'logging.debug(\1)',line)
            sys.stdout.write(line)
    
    if __name__=='__main__':
        convert(sys.argv[1:])
    

You could call the script this way

    
    
    % print2log.py *.py
    

It converts the scripts in-place, and makes a backup file which ends with `~`.

Note that the regex converts

    
    
    #print 'foo'   -->  logging.debug('foo')
    

but adds an extra set of parentheses if the print statement already had one:

    
    
    #print('foo')  --> logging.debug(('foo'))
    

It also screws up multi-line print statements:

    
    
    #print('''foo        logging.debug(('''foo)
    #bar''')       -->   #bar''')
    

Fixing this is a much harder problem, requiring parsing the comments and using
something smarter than regex, which can't handle nested parentheses properly.
I think you could do it with
[tokenize](http://docs.python.org/library/tokenize.html), and with code
similar in spirit to
[reindent.py](http://svn.python.org/projects/python/trunk/Tools/scripts/reindent.py),
but it would take some time and thought to get it right.

