How to open adb shell and execute commands inside

2019-04-02 07:23发布

问题:

I am trying to execute adb shell commands in python using subprocess.Popen

Example: Need to execute 'command' in adb shell. While executing manually, I open the command window and execute as below and it works.

>adb shell
#<command>

In Python I am using as below but the process is stuck and doesn't give output

subprocess.Popen('adb shell <command>)

Tried executing manually in command window, same result as python code,stuck and doesn't give output

>adb shell <command>

I am trying to execute a binary file in background(using binary file name followed by &) in the command.

回答1:

Found a way to do it using communicate() method in subprocess module

procId = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
procId.communicate('command1\ncommand2\nexit\n')


回答2:

use pexpect (https://pexpect.readthedocs.io/en/stable/)

adb="/Users/lishaokai/Library/Android/sdk/platform-tools/adb"
import pexpect
import sys, os
child = pexpect.spawn(adb + " shell")
child.logfile_send = sys.stdout

while True:
  index = child.expect(["$","@",pexpect.TIMEOUT])
  print index
  child.sendline("ls /storage/emulated/0/")
  index = child.expect(["huoshan","google",pexpect.TIMEOUT])
  print index, child.before, child.after
  break


回答3:

Ankur Kabra, try the code below:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
command = 'adb devices'
p = subprocess.Popen(command, shell=True,
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
print 'standard output: %s \n error output: %s \n',(stdout,stderr)

and you will see the error output.

Usually it will tell you:

 /bin/sh: adb: command not found

which means, shell can not excute adb command. so, adding adb to your PATH or writing the full path of adb will solve the problem.

May help.