cjg123 cjg123 -4 years ago 163
Python Question

Get number of files within Android directory using adb shell

I am currently trying to use the following python code to get the number of files within a directory.

output = subprocess.check_output(["adb", "shell", "cd /sdcard/Dir/Subdir", "find . -type f | wc -l"])
print output

However, I am getting the output:

/system/bin/sh: cd: too many arguments


But If I enter the following in command prompt, I get the desired result (14 files):

adb shell
cd /sdcard/Dir/Subdir
find . -type f | wc -l

Any idea how to integrate the command line code into python?

Answer Source

if you pass arguments to check_output in a list (not in a string), then if you pass arguments with spaces they will be quoted.

But that's not the main problem here.

You're running adb shell in check_output, but next commands should be passed through proper command line or standard input of your shell.

You could try the following (untested):

output = subprocess.check_output(["adb", "shell", "cd /sdcard/Dir/Subdir", "&&","find . -type f | wc -l"])

(&& tells the shell to chain cd with find instead of passing all arguments to cd)

or run your shell interactively, and pass the commands like if you typed them (use Popen for that):

p = subprocess.Popen(["adb", "shell"],stdin=subprocess.PIPE)
out,err = p.communicate("cd /sdcard/Dir/Subdir\nfind . -type f | wc -l\n")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download