Python如何通過subprocess調用adb命令詳解
前言
本文主要給大家介紹了關于使用Python通過subprocess調用adb命令,subprocess包主要功能是執(zhí)行外部命令(相對Python而言)。和shell類似。
換言之除了adb命令外,利用subprocess可以執(zhí)行其他的命令,比如ls,cd等等。
subprocess 可參考: https://docs.python.org/2/library/subprocess.html
在電腦上裝好adb工具,配置好adb的環(huán)境變量,先確保shell中可以調用adb命令。
代碼示例
Python2.7
類 Adb,封裝了一些adb的方法
import os import subprocess class Adb(object): """ Provides some adb methods """ @staticmethod def adb_devices(): """ Do adb devices :return The first connected device ID """ cmd = "adb devices" c_line = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0] if c_line.find("List of devices attached") < 0: # adb is not working return None return c_line.split("\t")[0].split("\r\n")[-1] # This line may have different format @staticmethod def pull_sd_dcim(device, target_dir='E:/files'): """ Pull DCIM files from device """ print "Pulling files" des_path = os.path.join(target_dir, device) if not os.path.exists(des_path): os.makedirs(des_path) print des_path cmd = "adb pull /sdcard/DCIM/ " + des_path result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() print result print "Finish!" return des_path @staticmethod def some_adb_cmd(): p = subprocess.Popen('adb shell cd sdcard&&ls&&cd ../sys&&ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE) return_code = p.poll() while return_code is None: line = p.stdout.readline() return_code = p.poll() line = line.strip() if line: print line print "Done"
some_adb_cmd方法執(zhí)行一連串的命令。各個命令之間用&&連接。
接著是一個死循環(huán),將執(zhí)行結果打印出來。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關文章
Python while循環(huán)使用else語句代碼實例
這篇文章主要介紹了Python while循環(huán)使用else語句代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-02-02python中自定義異常/raise關鍵字拋出異常的案例解析
在編程過程中合理的使用異??梢允沟贸绦蛘5膱?zhí)行,本篇文章給大家介紹python中自定義異常/raise關鍵字拋出異常案例解析,需要的朋友可以參考下2024-01-01Python基于正則表達式實現檢查文件內容的方法【文件檢索】
這篇文章主要介紹了Python基于正則表達式實現檢查文件內容的方法,可實現針對文件中import強制依賴的文件關系檢索,涉及Python文件目錄的遍歷及正則匹配相關操作技巧,需要的朋友可以參考下2017-08-08