Ankur
Ankur

Reputation: 195

How to open adb shell and execute commands inside shell using python

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.

Upvotes: 6

Views: 27459

Answers (3)

Ankur
Ankur

Reputation: 195

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')

Upvotes: 6

kaitian521
kaitian521

Reputation: 578

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

Upvotes: 1

shitoujizu
shitoujizu

Reputation: 69

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.

Upvotes: 0

Related Questions