How to open adb shell and execute commands inside

2019-04-02 07:26发布

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.

3条回答
beautiful°
2楼-- · 2019-04-02 08:01

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')
查看更多
唯我独甜
3楼-- · 2019-04-02 08:10

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.

查看更多
Emotional °昔
4楼-- · 2019-04-02 08:17

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
查看更多
登录 后发表回答