最近看到一些代码中总是有者/* under construction !*/这样的注释,于是也想写出这样效果的脚本。
如果原来的代码为:
#ifdef AAA//AAA
a = a + 1
#ifdef BBB//BBB
b = a + 1
#else //BBB
b = 100
#endif //BBB
c = 999
#endif //AAA
想要达到的效果是:
#ifdef AAA//AAA
/* under construction !*/
#ifdef BBB//BBB
/* under construction !*/
#else //BBB
/* under construction !*/
#endif //BBB
/* under construction !*/
#endif //AAA
最终的Python脚本程序如下,该脚本有一种情况下没有考虑,即同一行预编译语句中包含有多个宏控制下的处理,本脚本默认是不将代码修改为注释。
# -*- coding: cp936 -*-
def fileEncode(sourceFile,key,bForce = False):
"""replace the line in the scope of micro
para1:the target file
para2:the micro
para3:if force to parse
"""
try:
fp = open(sourceFile,'r')
lines = fp.readlines()
fp.close()
except:
print "Can't open File %s." % sourceFile
return
find = False
text = ""
replaceString = "/* under construction !*/\n"
numofMicro = 0
micro_start = "#if"
micro_mid = "#el"
micro_end = "#endif"
orStr = "||"
andStr = "&&"
for line in lines:
if find == False:
if micro_start in line:
if (key in line):
if not(andStr in line) and not(orStr in line) or bForce:
find = True
numofMicro += 1
text += line
else:
if micro_end in line:
numofMicro -= 1
if numofMicro == 0:
find = False
text += line
else:
if micro_start in line or micro_mid in line:
numofMicro += 1
text += line
else:
text += replaceString
#rewrite the file
try:
fp2 = open(sourceFile,'w')
fp2.write(text)
fp2.close
except:
print "Can't write file %s" % sourceFile
if __name__ == "__main__":
key = '__MMI_VIDEO_PLAYER__'
sourceFile = '复件 1.c'
fileEncode(sourceFile,key)
...