简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM