使用pure-python-adb的device.shell时字符串替换失效求助
问题原因与解决办法
为什么拼接字符串会失效?
你拼接出来的字符串多了一层单引号,实际传给device.shell()的内容是'input touchscreen tap 476 421'(包含首尾的单引号)。这相当于在ADB shell里执行一个带单引号包裹的整串内容,系统会把这个带引号的字符串当成一个完整的命令名,而不是input命令加上后续参数,自然无法识别执行。
对比两种写法的本质区别:
- 正常工作的写法:
device.shell('input touchscreen tap 240 856'),这里的单引号是Python定义字符串的语法,实际传给ADB shell的命令是input touchscreen tap 240 856(无外层单引号)。 - 你的错误写法:拼接后的字符串自带单引号,导致ADB shell收到的是被引号包裹的内容,命令逻辑完全错误。
正确的实现方式
方式1:去掉多余单引号,直接拼接
SomeStr = "input touchscreen tap " + str(476) + " " + str(421) device.shell(SomeStr)
方式2:用f-string(Python3.6+推荐)
语法更简洁易读:
x, y = 476, 421 cmd = f"input touchscreen tap {x} {y}" device.shell(cmd)
方式3:用str.format()
兼容更早版本的Python:
cmd = "input touchscreen tap {} {}".format(476, 421) device.shell(cmd)
内容的提问来源于stack exchange,提问作者arbus
相关产品推荐
相关产品推荐

