Python通过subprocess调用adb命令详解
本文详解如何利用Python的subprocess模块调用adb命令,实现Android设备的自动化管理。通过封装Adb类,演示了如何执行设备列表查询、文件拉取及复杂Shell命令链。文章提供Python 2.7环境下的完整代码示例,涵盖进程创建、标准输出处理及结果解析,适用于需要批量操作Android设备的开发场景。
前言
本文主要介绍如何在Python中利用subprocess模块调用adb命令。subprocess包的核心功能是执行外部命令(相对于Python解释器而言),其工作方式与Shell脚本类似。
换言之,除了adb命令外,利用subprocess还可以执行其他系统命令,例如ls、cd等。
关于subprocess模块的详细文档,可参考:https://docs.python.org/2/library/subprocess.html
在电脑上安装好adb工具,并配置好adb的环境变量,先确保在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方法执行一连串的命令。各个命令之间用&&连接。
接着是一个死循环,将执行结果打印出来。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对本站的支持。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













