1+ #!/usr/bin/env python
2+ # -*- coding: utf-8 -*-
3+ '''
4+ Created on 2015年1月23日
5+
6+ @author: xuxu
7+ '''
8+
9+ import os
10+ import platform
11+ import re
12+ import subprocess
13+ import time
14+
15+ import exception
16+
17+ #判断系统类型,windows使用findstr,linux使用grep
18+ system = platform .system ()
19+ if system is "Windows" :
20+ find_util = "findstr"
21+ else :
22+ find_util = "grep"
23+
24+ #判断是否设置环境变量ANDROID_HOME
25+ if "ANDROID_HOME" in os .environ :
26+ if system == "Windows" :
27+ command = os .path .join (os .environ ["ANDROID_HOME" ], "platform-tools" , "adb.exe" )
28+ else :
29+ command = os .path .join (os .environ ["ANDROID_HOME" ], "platform-tools" , "adb" )
30+ else :
31+ raise EnvironmentError (
32+ "Adb not found in $ANDROID_HOME path: %s." % os .environ ["ANDROID_HOME" ])
33+
34+ #adb命令
35+ def adb (args ):
36+ cmd = "%s %s" % (command , str (args ))
37+ return subprocess .Popen (cmd , shell = True , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
38+
39+ #adb shell命令
40+ def shell (args ):
41+ cmd = "%s shell %s" % (command , str (args ))
42+ return subprocess .Popen (cmd , shell = True , stdout = subprocess .PIPE , stderr = subprocess .PIPE )
43+
44+ #获取设备状态
45+ def get_state ():
46+ return adb ("get-state" ).stdout .read ().split ("\r \n " )[- 2 ]
47+
48+ #获取对应包名的pid
49+ def get_app_pid (pkg_name ):
50+ if system is "Windows" :
51+ string = shell ("ps | findstr %s$" % pkg_name ).stdout .read ()
52+
53+ string = shell ("ps | grep -w %s" % pkg_name ).stdout .read ()
54+
55+ if string == '' :
56+ return "the process doesn't exist."
57+
58+ pattern = re .compile (r"\d+" )
59+ result = string .split (" " )
60+ result .remove (result [0 ])
61+
62+ return pattern .findall (" " .join (result ))[0 ]
63+
64+ #杀掉对应包名的进程
65+ def kill_process (pkg_name ):
66+ pid = get_app_pid (pkg_name )
67+
68+ result = shell ("kill %s" % str (pid )).stdout .read ().split (": " )[- 1 ]
69+
70+ if result != "" :
71+ raise exception .SriptException ("Operation not permitted or No such process" )
72+
73+ #获取设备上当前应用的包名与activity
74+ def get_focused_package_and_activity ():
75+ pattern = re .compile (r"[a-zA-Z0-9\.]+/.[a-zA-Z0-9\.]+" )
76+ out = shell ("dumpsys window w | %s \/ | %s name=" % (find_util , find_util )).stdout .read ()
77+
78+ return pattern .findall (out )[0 ]
79+
80+ #获取当前应用的包名
81+ def get_current_package_name ():
82+ return get_focused_package_and_activity ().split ("/" )[0 ]
83+
84+ #获取当前设备的activity
85+ def get_current_activity ():
86+ return get_focused_package_and_activity ().split ("/" )[- 1 ]
87+
88+ #时间戳
89+ def timestamp ():
90+ return time .strftime ('%Y-%m-%d-%H-%M-%S' ,time .localtime (time .time ()))
91+
92+ #连接设备
93+ # adb("kill-server").wait()
94+ # adb("start-server").wait()
95+ adb ("wait-for-device" )
96+
97+ if get_state () != "device" :
98+ raise exception .SriptException ("Device not run" )
99+
100+
101+ if __name__ == "__main__" :
102+ pass
0 commit comments