Python如何通过subprocess调用adb命令详解

yipeiwu_com6年前Python基础

前言

本文主要给大家介绍了关于使用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方法执行一连串的命令。各个命令之间用&&连接。

接着是一个死循环,将执行结果打印出来。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

python嵌套字典比较值与取值的实现示例

python嵌套字典比较值与取值的实现示例

前言 本文通过示例给大家介绍了python嵌套字典比较值,取值,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧。 示例代码 #取值import types allGu...

python global关键字的用法详解

最近刚好有朋友遇到个global相关的问题,这里简单学习一下global关键字的用法。 想要更好的了解global关键字,首先要熟悉python的全局变量与局部变量的概念。global关...

Python远程桌面协议RDPY安装使用介绍

RDPY 是基于 Twisted Python 实现的微软 RDP 远程桌面协议。 RDPY 提供了如下 RDP 和 VNC 支持: ●RDP Man In The Middle pro...

Python enumerate索引迭代代码解析

本文研究的主要是Python enumerate索引迭代的问题,具体介绍如下。 索引迭代 Python中,迭代永远是取出元素本身,而非元素的索引。 对于有序集合,元素确实是有索引的。...

python文件的md5加密方法

本文实例讲述了python文件的md5加密方法。分享给大家供大家参考,具体如下: 简单模式: from hashlib import md5 def md5_file(name):...