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

yipeiwu_com5年前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设计】的支持。

相关文章

完美解决Python2操作中文名文件乱码的问题

完美解决Python2操作中文名文件乱码的问题

Python2默认是不支持中文的,一般我们在程序的开头加上#-*-coding:utf-8-*-来解决这个问题,但是在我用open()方法打开文件时,中文名字却显示成了乱码。 我先给大家...

numpy matrix和array的乘和加实例

1. 对于数组array 乘 就是对应位置的元素相乘: X1 = np.array([[1,2], [3, 4]]) X2 = X1 print X2*X1 [[ 1 4] [ 9...

用python与文件进行交互的方法

本文介绍了用python与文件进行交互的方法,分享给大家,具体如下: 一.文件处理 1.介绍 计算机系统:计算机硬件,操作系统,应用程序 应用程序无法直接操作硬件,通过操作系统来操作文...

在windows下Python打印彩色字体的方法

本文讲述了Python在windows下打印彩色字体的方法。分享给大家供大家参考,具体如下: ############################################...

对python实时得到鼠标位置的示例讲解

对python实时得到鼠标位置的示例讲解

如下所示: #先下载pyautogui库,pip install pyautogui import os,time import pyautogui as pag try: wh...