【发布时间】:2010-12-10 15:36:43
【问题描述】:
我现在正在开发一个框架,我想使用日志记录。但是,框架的开发者一直在使用 print 语句进行调试,并且在生产版本中都被注释掉了。我想知道,有没有人知道一个正则表达式来找到这些,并将它们转换为记录调用。
这是我目前的想法:
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()
虽然这似乎不起作用。我的正则表达式远非出色,有人可以帮忙吗?
【问题讨论】:
-
我认为您只需要在正则表达式中使用
.*而不是*。 (如果没有那个改变,这段代码就不会为我运行。) -
另外,这是
sed或perl中的单行代码。例如,perl -p -i.orig -e 's/#print (.*)/logging.debug(\1)/' FILE...。当您的程序只有一行并且您从不打算再次阅读它时,Perl 处于最佳状态。 ;)
标签: python regex debugging logging