将Python打印语句转换为日志记录
我正在处理一个很大的代码库,这个代码库使用打印语句来记录日志,而不是使用Python自带的日志功能。我在想,有没有什么推荐的方法可以把这些打印语句都转换成调用logging.info?很多打印语句分布在好几行,所以任何解决方案都需要处理这种情况,并且最好能保持原来的格式。
我查过Python的rope工具,但它似乎没有把像print这样的语句转换成函数调用的功能。
2 个回答
1
只需要在你的代码开始之前加上这几行,就可以记录下它输出的所有内容。我觉得你可能在找这样的东西。
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."
3
你可以使用 2to3
工具,只 针对打印语句转换为打印函数进行修复。
2to3 --fix=print [yourfiles] # just displays the diff on stdout
2to3 --fix=print [yourfiles] --write # also saves the changes to disk
这样应该能自动处理那些奇怪的情况,然后把打印函数转换为日志函数就可以简单地用查找和替换的方法来完成,比如用 sed
工具。
如果你因为某种原因没有 2to3
脚本的快捷方式,可以直接把 lib2to3
当作模块来运行:
python -m lib2to3 --fix=print .