在python中启动adb命令

时间:2017-11-13 11:41:45

标签: android python python-3.x adb

我尝试在没有自定义模块的python中启动adb命令。

尝试:

process = subprocess.Popen('cmd.exe',   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, shell=True)
process.stdin.write("adb shell uninstall com.q.q".encode("utf8"))
process.stdin.write("adb shell install C:\\...\\qwerty.apk".encode("utf8"))

但这不起作用。代码完成没有结果

1 个答案:

答案 0 :(得分:1)

无法使用您的确切命令进行测试,但效果很好:

import subprocess

process = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, shell=True)
o,e = process.communicate(b"dir\n")
print(o)

(我得到了我目录的内容)

因此,对于您的示例,您在发送命令时错过了行终止符。命令不会发送到cmd程序,管道在此之前就会被破坏。

这会更好:

import subprocess

process = subprocess.Popen('cmd.exe',   stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None)
process.stdin.write(b"adb shell uninstall com.q.q\n")
process.stdin.write(b"adb shell install C:\\...\\qwerty.apk\n")
o,e = process.communicate()

但这是一种非常奇怪的运行命令的方法。只需使用check_call,正确分割args:

subprocess.check_call(["adb","shell","uninstall","com.q.q"])
subprocess.check_call(["adb","shell","install",r"C:\...\qwerty.apk"])