1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > python执行adb命令_Python脚本之ADB命令(一)

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

时间:2023-03-19 16:53:04

相关推荐

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.

参数既可以是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 分别表示程序的标准输入、输出、错误句柄

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。