【问题标题】:subprocess.check_output fails to execute a command but the same works in windowssubprocess.check_output 无法执行命令,但在 Windows 中同样有效
【发布时间】:2017-08-11 01:15:03
【问题描述】:

我正在尝试将两个设备连接到我的电脑并使用 python 和 adb 在它们上运行一些命令。 当我从命令提示符运行命令时,它运行良好,但是当我将它们放入 python 脚本时,它们给了我错误。 这一直导致错误:

from subprocess import check_output, CalledProcessError
try:
    adb_ouput = check_output(["adb","devices","-l","|", "grep", "\"model\""])
    print adb_ouput
except CalledProcessError as e:
    print e

我得到的错误信息是这样的:

Usage: adb devices [-l]
Command '['adb', 'devices', '-l', '|', 'grep', '"model"']' returned non-zero exit status 1

当我尝试不使用 grep 命令的相同代码时,它可以工作

adb_ouput = check_output(["adb","devices","-l"])

它给了我正确的输出。

当我在 Windows 命令提示符中尝试相同的操作时,它工作正常(我将 grep 替换为 FINDSTR,因为我在 Windows 中使用它,并且我也尝试在 python 脚本中执行相同的操作,使用 'shell = True' 也没有。)

例如:

adb devices -l | FINDSTR "model"

这给了我一个没有任何问题的输出。 我得到的输出是

123ab6ef 设备产品:xxxxxxxxx 型号:xxxxxxxxx 设备:xxxxxxxxx

bd00051a4 设备产品:yyyyyyyyyy 型号:yyyyyyyyyy 设备:yyyyyyyyy

我试图了解我在哪里出错,但无法弄清楚。 到目前为止,我已经检查了文档:https://docs.python.org/3/library/subprocess.html https://docs.python.org/3/library/subprocess.html#subprocess.CalledProcessError 这些只是给我错误代码。

我也看过这些答案: Python, adb and shell execution query 我从这里进行了一些错误检查并添加到我的代码中。

Python subprocess.check_output(args) fails, while args executed via Windows command line work OK python check_output fails with exit status 1 but Popen works for same command

我想我已经很接近了,但就是不能把我的手指放在它上面。 任何帮助将不胜感激。

【问题讨论】:

    标签: android python shell subprocess adb


    【解决方案1】:

    第一

    adb_ouput = check_output(["adb","devices","-l","|", "grep", "\"model\""])
    

    当然需要shell=True,但即使这样,它也不等同于

    adb devices -l | FINDSTR "model"
    

    当使用check_output 时,您实际上将"model" 作为grep 参数传递,但您应该只传递model"model" 不在您的输出中(带引号),因此grep 找不到它,并返回退出代码1,这对于grep 来说并不是真正的错误,但会使check_output 触发异常,因为它需要@987654333 @。

    所以我会将此作为快速修复:

    adb_ouput = check_output(["adb","devices","-l","|", "grep", "model"],shell=True)
    

    作为一个长修复,我会直接用 python 执行grep 命令。

    adb_output = check_output(["adb","devices","-l"])
    for l in adb_output.splitlines():
         if "model" in l:
             print(l)
    

    【讨论】:

    • 我也试过不带引号,但失败了。我坚持在 python 中过滤我的输出,而不是使用 grep。感谢您的回答。
    • 我不明白为什么它不起作用,但第二种解决方案还是更好。你甚至可以想象把它放在没有grep 的机器上。
    猜你喜欢
    • 2021-11-13
    • 2017-08-17
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多