Ondřej Baše
Ondřej Baše

Reputation: 7

Using "adb shell" in Python

So I decided to create very simple "ADB Installer" Python app for installing builds and taking screenshots on Android devices using the os.system / os.popen lines, like for example:

os.system("adb connect " + IP)

etc. But now I am kind of stuck, because i need to send this (which works OK in bash script I use as a base for my Python app):

  adb shell "
  cd [path] 
  rm -r [app name]
  exit
  "

How do I do this using os.system / os.popen please? (I really tried to avoid using adb-shell and other Python implementations, but if there is no other way then I will try it). Thanks!

Upvotes: 0

Views: 4521

Answers (2)

St0rm
St0rm

Reputation: 401

Using subprocess:

from subprocess import run, PIPE

path = "[path]"
app_name = "[app name]"
commands_array = ["adb","shell", "rm", path + "/" + app_name , "&&", 
                  "ls", "-la", path]
try:
    result = run(commands_array, stdout=PIPE, stderr=PIPE, 
                  check=True, universal_newlines=True)
except Exception as e:
   print("An error occured:")
   print(e)

print(result.stdout)

Upvotes: 1

TankorSmash
TankorSmash

Reputation: 12767

Using triplequotes, you can get multiple lines within a string. Not sure if this'll work, but it's what I would try.

os.system("""adb shell "
  cd [path] 
  rm -r [app name]
  exit
  " """)

Upvotes: 0

Related Questions