在我們開發(fā)android程序過程中,很多時候 需要查看android的源碼是如何實現(xiàn)的。這個時候就需要把android的源碼加入到eclipse中,那么在我們通過Git和repo獲取到android源碼之后,就需要把java文件提取出來,并放到androidSDK子目錄source下。如果手工來提取這些java文件是很耗費時間的,所以我們可以寫個python腳本來自動提取android源碼中的java文件,如下:
from __future__ import with_statement # for Python < 2.6
import os
import re
import zipfile
# open a zip file
DST_FILE = 'sources.zip'
if os.path.exists(DST_FILE):
print DST_FILE, "already exists"
exit(1)
zip = zipfile.ZipFile(DST_FILE, 'w', zipfile.ZIP_DEFLATED)
# some files are duplicated, copy them only once
written = {}
# iterate over all Java files
for dir, subdirs, files in os.walk('.'):
for file in files:
if file.endswith('.java'):
# search package name
path = os.path.join(dir, file)
with open(path) as f:
for line in f:
match = re.match(r'\s*package\s+([a-zA-Z0-9\._]+);', line)
if match:
# copy source into the zip file using the package as path
zippath = match.group(1).replace('.', '/') + '/' + file
if zippath not in written:
written[zippath] = 1
zip.write(path, zippath)
break;
zip.close()
來自:http://blog.csdn.net/dongfengsun/archive/2009/10/17/4691062.aspx