在 Python 中使用 "adb shell"

Using "adb shell" in Python

所以我决定创建非常简单的“ADB 安装程序”Python 应用程序,用于使用 os.system / os.popen 行在 Android 设备上安装构建和截屏,例如:

os.system("adb connect " + IP)

等但现在我有点卡住了,因为我需要发送这个(在我用作我的 Python 应用程序的基础的 bash 脚本中工作正常):

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

请问如何使用 os.system / os.popen 执行此操作? (我真的尽量避免使用 adb-shell 和其他 Python 实现,但如果没有其他方法,我会尝试)。 谢谢!

使用三引号,您可以获得一个字符串中的多行。不确定这是否有效,但这是我会尝试的。

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

使用子进程:

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)