Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 利用Python自动清除Android工程中的多余资源

我们直接在公司项目中使用,效果良好!分享出脚本代码,希望对Android研发的同学有帮助。提示,初学Python,开发环境是Sublime Text 2,直接Ctrl+B的,其他环境下没调试过。应该差不多^^#################################################
#环境: win + python 2.7
#作者:马波
#邮箱:mabo02@baidu.com
#部门:hao123-无线
#说明:首次使用时lint分析会耗几分钟,请耐心等待。
#      使用前先clean工程,确保工程bin下重新生成dex,
#      以便lint进行分析。如果要lint重新分析多余
#      资源,需要删掉(2)txt记录文件,(1)(3)(4)需要
#      根据我们的实际工程手动设置。
#      如果清除资源后,工程缺少文件而报错(极少
#      情况),尝试通过svn恢复该文件即可。
#################################################
import subprocess   
import re
import os
import time
import thread #(1)工程位置
projectPath="D:/hao123/code/client-android"
#(2)lint输出txt记录文件
txt="D:/hao123_unused_res.txt"
#(3)正则表达式,清除drawable和layout下多余的jpg/png/xml,
# 并且排除以sailor_|wenku_|zeus_|bdsocialshare_|floating_life_|weather_info_icon_|anthology_开头的文件
regex = re.compile(r"^res\(drawable(-land)?(-[xn]?[mhlo](dpi))|layout)?\(?!(sailor_|wenku_|zeus_|bdsocialshare_|floating_life_|weather_info_icon_|anthology_))[0-9a-zA-Z_.]*.(jpg|png|xml)", re.IGNORECASE)
#(4)lint.bat的位置
lint="D:/sdk/tools/lint.bat"isgotTxt=False
def timer(interval): 
    while not isgotTxt:
        print "Lint is analyzing: %s"%time.ctime() 
        time.sleep(interval)if not os.path.exists(txt):
    thread.start_new_thread(timer, (5,))
    cmd=lint+" --check "UnusedResources" ""+ projectPath +"" >"+txt
    p = subprocess.Popen(cmd, shell = True,stdout = subprocess.PIPE,stdin = subprocess.PIPE,stderr = subprocess.PIPE)       
    p.wait()fobj=open(txt,"r")
isgotTxt=True
i=0
j=0
for line in fobj:
    #print str(i)+":"+line
    match=regex.match(line)
    if match:
        i=i+1
        filename=projectPath+"/"+match.group().replace("\","\/")
        try:
            print filename
            os.remove(filename)
            j=j+1
            print "was deleted!"
        except WindowsError:
            print "is not exists"
            passprint "Total Unused Resources = "+str(i)
print "Total deleted Resources = "+str(j)--------------------------------------分割线 --------------------------------------无需操作系统直接运行 Python 代码  http://www.linuxidc.com/Linux/2015-05/117357.htmCentOS上源码安装Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm《Python核心编程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码] http://www.linuxidc.com/Linux/2013-11/92693.htmPython脚本获取Linux系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm在Ubuntu下用Python搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htmPython 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm--------------------------------------分割线 --------------------------------------更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-07/120535.htm