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中的列表生成式与生成器学习教程

列表生成式 即创建列表的方式,最笨的方法就是写循环逐个生成,前面也介绍过可以使用range()函数来生成,不过只能生成线性列表,下面看看更为高级的生成方式: >>>...

Django中Forms的使用代码解析

Django中Forms的使用代码解析

本文研究的主要是Django中Forms的使用,具体如下。 创建文件do.html {% extends 'base.html' %} {% block mainbody %}...

Python中获取网页状态码的两个方法

第一种是用urllib模块,下面是例示代码: 复制代码 代码如下: import urllib status=urllib.urlopen("//www.jb51.net").code...

python使用numpy实现直方图反向投影示例

python使用numpy实现直方图反向投影示例

最近跟着OpenCV2-Python-Tutorials在学习python_opencv中直方图的反向投影时,第一种方法是使用numpy实现将图中的红色玫瑰分割出来,教程给的代码缺了一句...

python中的lambda表达式用法详解

本文实例讲述了python中的lambda表达式用法。分享给大家供大家参考,具体如下: 这里来为大家介绍一下lambda函数。 lambda 函数是一种快速定义单行的最小函数,是从 Li...