1import os, subprocess, tempfile
2import time
3
4ANDROID_TMPDIR = '/data/local/tmp/Output'
5ADB = os.environ.get('ADB', 'adb')
6
7verbose = False
8if os.environ.get('ANDROID_RUN_VERBOSE') == '1':
9    verbose = True
10
11def adb(args, attempts = 1):
12    if verbose:
13        print args
14    tmpname = tempfile.mktemp()
15    out = open(tmpname, 'w')
16    ret = 255
17    while attempts > 0 and ret != 0:
18      attempts -= 1
19      ret = subprocess.call([ADB] + args, stdout=out, stderr=subprocess.STDOUT)
20      if attempts != 0:
21        ret = 5
22    if ret != 0:
23      print "adb command failed", args
24      print tmpname
25      out.close()
26      out = open(tmpname, 'r')
27      print out.read()
28    out.close()
29    os.unlink(tmpname)
30    return ret
31
32def pull_from_device(path):
33    tmp = tempfile.mktemp()
34    adb(['pull', path, tmp], 5)
35    text = open(tmp, 'r').read()
36    os.unlink(tmp)
37    return text
38
39def push_to_device(path):
40    # Workaround for https://code.google.com/p/android/issues/detail?id=65857
41    dst_path = os.path.join(ANDROID_TMPDIR, os.path.basename(path))
42    tmp_path = dst_path + '.push'
43    adb(['push', path, tmp_path], 5)
44    adb(['shell', 'cp "%s" "%s" 2>&1' % (tmp_path, dst_path)], 5)
45