[英]How to open adb shell and execute commands inside shell using python
我正在嘗試使用subprocess.Popen在python中執行adb shell命令
示例:需要在adb shell中執行“命令”。 手動執行時,我打開命令窗口並按如下所示執行,它可以工作。
>adb shell
#<command>
在Python中,我使用如下,但過程卡住了,沒有給出輸出
subprocess.Popen('adb shell <command>)
嘗試在命令窗口中手動執行,結果與python代碼相同,卡住並且不提供輸出
>adb shell <command>
我正在嘗試在命令中在后台執行二進制文件(使用二進制文件名,后跟&)。
在子流程模塊中找到了使用communication()方法做到這一點的方法
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
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
的完整路徑將解決此問題。
可能有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.