python执行adb命令_Python脚本之ADB命令(一)

Android 调试桥(adb)是多种用途的工具,该工具可以帮助你管理设备或模拟器 的状态。实际运用中我们可以通过adb进行shell命令的相关操作,但是大部分这需要在CMD命令窗口一次又一次的重复输入,为了提高日常工作效率,今天给大家普及一下如何通过脚本的形式一次编辑,多次维护来解决日常adb命令重复输入的尴尬境遇。

首先,我们需要在电脑上装好adb工具,配置好adb的环境变量,先确保shell中可以调用adb命令。其次,编辑脚本我采用Python这门胶水语言,为什么用Python呢?因为上手容易,好用啊!

1、Python编辑脚本要想调用windows系统中的CMD窗口,可以有两种方法:

a、import os

b、import subprocess

os和subprocess模块二选一即可,有些人可能问为什么都可以实现对CMD命令窗口的调用还有2种模块支持。主要是因为os是Python2.4之前的产物且其特征是“阻塞式”,subprocess是从Python2.4之后才加入的模块其特征“非阻塞式”。

2、Python如何通过subprocess调用adb命令详解,附:subprocess官方文档。

1)概述

subprocess模块是在2.4版本中新增的,官方文档中描述为可以用来替换以下函数:

os.system、os.spawn、os.popen、popen2

2)参数

官方对于subprocess模块的参数解释如下:

args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

78ed2b45784d

参数既可以是string,也可以是list。

subprocess.Popen([“cat”,”test.txt”])

subprocess.Popen(“cat test.txt”, shell=True)

对于参数是字符串,需要指定shell=True

3)使用示例

其中subprocess.call()用于代替os.system(),但是这2个函数无法返回命令的输出。只会返回函数运行成功与否的0或其他值。示例:import subprocess

returnCode = subprocess.call('adb devices')

print returnCode

subprocess.check_outputimport subprocess

# returns output as byte stringreturned_output = subprocess.check_output(cmd)# using decode() function to convert byte string to string

cmd = "date"

print('Current date is:', returned_output.decode("utf-8"))

subprocess.Popen的使用

1.执行结果保存在文件cmd ="adb shell ls /sdcard/ | findstr aa.png"

fhandle = open(r"e:\aa.txt","w")

pipe = subprocess.Popen(cmd, shell=True, stdout=fhandle).stdout

fhandle.close()

2.执行结果使用管道输出import subprocess

cmd = 'adb help'

pi= subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)

print pi.stdout.read()

注:stdin, stdout, stderr 分别表示程序的标准输入、输出、错误句柄

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值