查找并替换文件内容-编译选项的修改

前言: 在实际的应用中,很容易出现的需求是通过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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值