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

2024-04-25 09:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图使用subprocess.Popen在python中执行adb shell命令

示例:需要在adb shell中执行'command'。当手动执行时,我打开命令窗口并按如下方式执行,它就工作了。

>adb shell
#<command>

在Python中,我使用如下所示,但是进程被卡住了,没有给出输出

subprocess.Popen('adb shell <command>)

尝试在命令窗口中手动执行,结果与python代码相同,卡住且不提供输出

>adb shell <command>

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


Tags: 文件代码命令示例进程方式二进制手动
3条回答

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的完整路径将解决问题。

可能有帮助。

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

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

使用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

相关问题 更多 >