Search code examples
androidpythonpython-2.7adbappium

How to run two adb shell commands via Python, but store output of only one?


I am [new to] using Python 2.7 on Windows 7 and I am trying to incorporate adb shell commands to access/change the directories on my Android device. What I need to do is get the size of a directory in Internal Storage, save that output as a variable, and then delete the directory. From my research I believe I should be using subprocess.Popen()to create the shell and then .communicate() to send the required commands. However I am currently only able to execute one of the commands: delete the directory. Below is the code that I used:

 import os, subprocess
 from subprocess import PIPE, Popen

 adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
 adb_shell.communicate('cd /sdcard\nrm -r "Directory to Delete"\nexit\n')

However, if I add another command by doing:

adb_shell.communicate('cd /sdcard\ndu -sh "Directory A"\nrm -r "Directory A"\nexit\n')

It does not work because I need to incorporate stdout = subprocess.PIPE to store the output of the du -sh "Directory A"command, but how do I go about doing that? If I add it like: adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE, stdout = subprocess.PIPE), it does not work. Any suggestions? ty!

Edit: The closest I've come to a solution (actually getting an output in the interpreter and removing the file afterwards) is with:

    adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
    adb_shell.communicate('cd /sdcard\ndu -sh "qpython"\nexit\n')
    output = adb_shell.stdout
    print output

    adb_shell = subprocess.Popen('adb shell', stdin = subprocess.PIPE)
    adb_shell.communicate('cd /sdcard\nrm -r "qpython"\nexit\n')

Which has an output of: '', mode 'rb' at 0x02B4D910>'


Solution

  • There is no reason for running both commands in the same shell session:

    print subprocess.check_output(["adb", "shell", "du -sh /sdcard/qpython"])
    subprocess.check_output(["adb", "shell", "rm -r /sdcard/qpython"])