歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 利用Python自動清除Android工程中的多余資源

利用Python自動清除Android工程中的多余資源

日期:2017/3/1 9:27:00   编辑:Linux編程

我們直接在公司項目中使用,效果良好!

分享出腳本代碼,希望對Android研發的同學有幫助。

提示,初學Python,開發環境是Sublime Text 2,直接Ctrl+B的,其他環境下沒調試過。應該差不多^^

#################################################
#環境: win + python 2.7
#作者:馬波
#郵箱:[email protected]
#部門: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"
pass

print "Total Unused Resources = "+str(i)
print "Total deleted Resources = "+str(j)

--------------------------------------分割線 --------------------------------------

無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm

CentOS上源碼安裝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.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

--------------------------------------分割線 --------------------------------------

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved