dump_packages_argparse

# -*- coding:utf-8 -*-
‘‘‘
Created on Jul 14, 2015

@author: yunguix
‘‘‘
import sys
import subprocess
import argparse

def shell(cmd, env=None):
    """Execute date command.

    return (return code, stderr, stdout)
    """
    p = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    (stdout, stderr) = p.communicate()
    return (p.returncode, stdout, stderr)

def devices():
    (ret_code, stdout, stderr) = shell(‘adb devices‘)
    if ret_code != 0:
        raise ADB_Exception(‘ADB return code = {0}\n-------------------\n{1}------------------‘.format(ret_code, stderr))
    adb_lines = [line.strip() for line in stdout.split(‘\n‘)]
    device_list = []
    if len(adb_lines) > 1:
        device_list = [line.split(‘\t‘)[0] for line in adb_lines[1:] if line != ‘‘]
#     print device_list
        return device_list

class ADB_Exception(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

class ADB_Device():
    d_params = {‘‘:‘allApps‘, ‘-3‘:‘thirdApps‘, ‘-s‘:‘systemApps‘} 

    def __init__(self, device_name=None, param=‘‘):
#         device_list = devices()
#         if len(device_list) == 0:
#             raise ADB_Exception(‘No devices connected.‘)
#         if device_name is None or len(device_list) == 1:
#             device_name = device_list[0]
#         elif device_name not in device_list:
#             raise ADB_Exception(‘Device="{0}" not found in ADB devices: {1}‘.format(device_name, ‘,‘.join(device_list)))
        self.device_name = device_name
        self.param = param    

    def list_packages(self):
        cmd = ‘adb -s {0} {1}‘.format(self.device_name, ‘shell pm list package ‘ + self.param)
        (_ret_code, stdout, _stderr) = shell(cmd)
        packages = stdout.split(‘package:‘)
        packages = [l.strip() for l in packages if l != ‘‘]
        return packages

    def dumpsys_package(self, package):
        cmd = r‘adb -s ‘ + self.device_name + ‘ shell dumpsys package ‘ + package
        (_ret_code, stdout, _stderr) = shell(cmd)
        text = [line.strip() for line in stdout.split(‘\n‘)]
        d_package = {}
        for line in text:
            if ‘versionName=‘ in line:
                ver = line.split(‘versionName=‘)[1].strip(‘‘)
                d_package[package] = ver
                break
        return d_package        

    def writeToExcel(self):
        from openpyxl import Workbook      

        wb = Workbook()
        ws = wb.get_active_sheet()
        ws.title = ADB_Device.d_params[self.param]

        ws.cell(‘A1‘).value = u‘index‘
        ws.cell(‘B1‘).value = u‘packagename‘
        ws.cell(‘C1‘).value = u‘version‘

        packages = self.list_packages()
        print len(packages)
        if len(packages) != 0:
            i = 0
            for each in packages:
                dictPKG = self.dumpsys_package(each)
#                 cmd = cmd = r‘adb -s ‘ + self.device_name + ‘ uninstall ‘ + each
#                 print cmd
#                 shell(cmd)
                ws.cell(row=i + 2, column=1).value = i + 1
                ws.cell(row=i + 2, column=2).value = each
                ws.cell(row=i + 2, column=3).value = dictPKG[each]
                wb.save(self.device_name + ‘_‘ + ADB_Device.d_params[self.param] + ‘.xlsx‘)
                i = i + 1
        else:
            print "!!!No " + ADB_Device.d_params[self.param] + ‘.‘

if __name__ == ‘__main__‘:
    parser = argparse.ArgumentParser(prog=‘dumpsys package‘,
        description=‘get package info of installed apps‘)

    parser.add_argument(‘--device‘,
                        help=‘Name of Android device from "adb devices" command‘)                        

    parser.add_argument(‘--c‘,
                        default=‘all‘,
                        choices=[‘all‘, ‘third‘, ‘system‘],
                        help=‘get all, third, system apps info‘)         

    parser.add_argument(‘--version‘, action=‘version‘, version=‘%(prog)s 1.0‘)

    args = parser.parse_args()
    device_name = args.device
    choice = args.c
    print device_name, choice

    device_list = devices()
    if device_list == []:
        print ‘Error: No Android devices are found by "adb devices" command.‘
        sys.exit(1)
    if device_name is None:
        device_name = device_list[0]
    elif device_name not in device_list:
        print ‘Error: "{0}" is not in the connectde device "{1}".‘.format(device_name, ‘, ‘.join(device_list))
        sys.exit(1)

    d_params = {‘all‘:‘‘, ‘third‘:‘-3‘, ‘system‘:‘-s‘}
    param = d_params[choice]
    device = ADB_Device(device_name=device_name, param=param)
    device.writeToExcel()
    print ‘Done.‘
时间: 2024-10-29 19:05:33

dump_packages_argparse的相关文章