1

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

2 Answers 2

1

It's not pretty but it works:

    lines = []
    get_restore_size = subprocess.Popen('adb shell du -sh /sdcard/qpython', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    for line in get_restore_size.stdout.readlines():
        lines.append(line)
        restore_size = (lines[0].strip('\t/sdcard/qpython\r\r\n'))
        print restore_size


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

Open to suggestions to improve!

Sign up to request clarification or add additional context in comments.

Comments

0

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"])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.