【IT168技术】在我们开发android程序过程中,很多时候 需要查看android的源码是如何实现的。这个时候就需要把android的源码加入到 eclipse中,那么在我们通过Git和repo获取到android源码之后,就需要把java文件提取出来,并放到android SDK子目录source下。如果手工来提取这些java文件是很耗费时间的,所以我们可以写个python脚本来自动提取android源码中的java文件,如下:
1from __future__ import with_statement # for Python < 2.6
2
3import os
4import re
5import zipfile
6
7# open a zip file
8DST_FILE = 'sources.zip'
9if os.path.exists(DST_FILE):
10 print DST_FILE, "already exists"
11 exit(1)
12zip = zipfile.ZipFile(DST_FILE, 'w', zipfile.ZIP_DEFLATED)
13
14# some files are duplicated, copy them only once
15written = {}
16
17# iterate over all Java files
18for dir, subdirs, files in os.walk('.'):
19 for file in files:
20 if file.endswith('.java'):
21 # search package name
22 path = os.path.join(dir, file)
23 with open(path) as f:
24 for line in f:
25 match = re.match(r'\s*package\s+([a-zA-Z0-9\._]+);', line)
26 if match:
27 # copy source into the zip file using the package as path
28 zippath = match.group(1).replace('.', '/') + '/' + file
29 if zippath not in written:
30 written[zippath] = 1
31 zip.write(path, zippath)
32 break;
33
34zip.close()
35
2
3import os
4import re
5import zipfile
6
7# open a zip file
8DST_FILE = 'sources.zip'
9if os.path.exists(DST_FILE):
10 print DST_FILE, "already exists"
11 exit(1)
12zip = zipfile.ZipFile(DST_FILE, 'w', zipfile.ZIP_DEFLATED)
13
14# some files are duplicated, copy them only once
15written = {}
16
17# iterate over all Java files
18for dir, subdirs, files in os.walk('.'):
19 for file in files:
20 if file.endswith('.java'):
21 # search package name
22 path = os.path.join(dir, file)
23 with open(path) as f:
24 for line in f:
25 match = re.match(r'\s*package\s+([a-zA-Z0-9\._]+);', line)
26 if match:
27 # copy source into the zip file using the package as path
28 zippath = match.group(1).replace('.', '/') + '/' + file
29 if zippath not in written:
30 written[zippath] = 1
31 zip.write(path, zippath)
32 break;
33
34zip.close()
35