Skip to content

Instantly share code, notes, and snippets.

@xebecnan
Created January 6, 2018 03:37
Show Gist options
  • Save xebecnan/441371936d41fccb7884497d62790a5c to your computer and use it in GitHub Desktop.
Save xebecnan/441371936d41fccb7884497d62790a5c to your computer and use it in GitHub Desktop.
reload_adb_devices.py
#!/usr/bin/python
import re
import sys
from subprocess import Popen, PIPE, STDOUT
def print_lines(tag, lines):
lines = str(lines).splitlines()
n = len(tag)
n += (4 - (n % 4)) % 4
tag = '%{}s'.format(n) % tag
indent = ' ' * n
for i, line in enumerate(lines):
print '{} | {}'.format(i==0 and tag or indent, line)
def exec_cmd(cmd):
print 'exec_cmd'
print_lines('CMD', cmd)
p = Popen(cmd, stdout=PIPE, stderr=STDOUT, shell=True)
out = []
for raw in iter(p.stdout.readline, b''):
out.append(raw)
p.wait()
code = p.returncode
val = ''.join(out)
print_lines('RET', code)
print_lines('OUT', val)
return code, val
def check_adb_devices():
code, val = exec_cmd('adb devices')
if code != 0:
return False
if not re.findall(r'^([0-9a-f]+)\s', val, re.M):
return False
return True
def try_load_devices():
for _ in xrange(3):
if check_adb_devices():
print 'ok'
return True
print 'reload'
code, val = exec_cmd('adb kill-server')
code, val = exec_cmd('adb start-server')
print 'fail to load devices'
return False
def main():
try_load_devices()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment