前言: 在实际的应用中,很容易出现的需求是通过Python来执行编译选项的替换工作,例如我现在想通过一个off/on 开关来控制文件test的sys.proj = true 这一行编译选项,在off的时候给它加上注释#,在on的时候去掉#,那么就可以通过以下python代码并在.sh中添加
python replace.py on/off来实现替换工作。
具体的代码如下:
#!/usr/local/bin/python
#coding:utf-8
import re
import os
import tempfile
import shutil
import sys
def replace(filePath,oldstr,newstr):
temp_file=tempfile.mktemp()
print ("tempfile name is","=>",temp_file) # 创建名称唯一的临时文件
file=open(temp_file,'w+') # 打开临时文件
old_file=filePath
if os.path.exists(old_file):
fopen=open(old_file,'r')
else:
print ("file %s not found" % old_file)
sys.exit()
for line in fopen:
if(re.match(oldstr,line)):
line = re.sub(oldstr,newstr,line) #替换原文件的内容
file.write(line) # 写入文件
fopen.close()
file.seek(0) # 回到启示位置
file.close()
# file1=open(temp_file,'r') #打开临时文件
# for readline in file1:
# print (readline) #打印临时文件内容
if os.path.exists(old_file):
os.remove(old_file) #删掉原文件
shutil.copy(temp_file,old_file) #copy临时文件到原文件
try:
os.remove(temp_file) #删掉临时文件
except OSError:
pass
#三个参数,第一个是文件名,第二个是要替换的字符串,第三个是需要替换成的字符串
def main():
if(sys.argv[1]=="on"):
replace('test','sys.proj = true ','#sys.proj = true ')
else:
replace('test','#sys.proj = true ','sys.proj = true ')
if(__name__ == "__main__"):
main()
说明:
1.直接替换需要的变量,并保存replace.py 就可以执行,
2.如何通过参数传入Py文件则可以用
sys.argv[0] //文件名
sys.argv[1] //第一个参数
sys.argv[2] //第二个参数以此类推
3.代码部分参考文章 http://www.cnblogs.com/belid/archive/2013/05/07/3064903.html