如何打开 adb shell 并使用 python 在 shell 中执行命令

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

我正在尝试使用 subprocess.Popen

在 python 中执行 adb shell 命令

示例:需要在adbshell中执行'command'。手动执行时,我打开命令 window 并按如下方式执行,它起作用了。

>adb shell
#<command>

在Python中,我使用如下,但过程卡住了,没有输出

subprocess.Popen('adb shell <command>)

尝试在命令 window 中手动执行,结果与 python 代码相同,卡住并且没有输出

>adb shell <command>

我正在尝试在命令中在后台执行一个二进制文件(使用二进制文件名后跟 &)。

Ankur Kabra,试试下面的代码:

#!/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)

你会看到错误输出。

通常它会告诉你:

 /bin/sh: adb: command not found

也就是说,shell不能执行adb命令。 因此,将 adb 添加到 PATH 或写入 adb 的完整路径将解决问题。

可能会有帮助。

使用预期 (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

在子进程模块中找到了使用 communicate() 方法的方法

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