欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2021-04-25 10:10:11|栏目: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 datetime中strptime用法详解

栏    目:Python代码

下一篇:python算法学习之基数排序实例

本文标题:Python如何通过subprocess调用adb命令详解

本文地址:http://www.codeinn.net/misctech/108275.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有