【问题标题】:How do I get the output of an adb shell command using gradle?如何使用 gradle 获取 adb shell 命令的输出?
【发布时间】:2016-12-05 21:38:54
【问题描述】:

A previous post 展示了如何获取使用 gradle 执行的 shell 命令的输出。但是,当我尝试将其应用于“adb shell”命令时,它会打印空行。例如,这个脚本:

task runTests {
    doLast {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'cmd' , '/c', 'dir', 'src'
        }
    print stdout
}

打印

Volume in drive C is Windows
Volume Serial Number is 0AEC-E2A0

Directory of C:\Users\mb\android\project

12/02/2016  12:37 PM    <DIR>          .
12/02/2016  12:37 PM    <DIR>          ..
12/02/2016  12:37 PM    <DIR>          androidTest
12/02/2016  12:37 PM    <DIR>          main
12/02/2016  12:37 PM    <DIR>          test
           0 File(s)              0 bytes
           5 Dir(s)  13,056,221,184 bytes free

但是这个:

task runTests {
    doLast {
        def stdout = new ByteArrayOutputStream()
        exec {
            commandLine 'cmd' , '/c', 'adb', 'shell' , 'ls'
        }
    print stdout
}

打印空行。它似乎为每一行输出打印一个空白行。如果我将命令更改为

commandLine 'cmd' , '/c', 'adb', 'shell' , 'ls' , 'acct'

然后它会打印更少的空白行,因为 'acct' 目录中的文件更少。如果我运行

adb shell ls acct

在 Windows 命令提示符中,它会打印

cgroup.clone_children
cgroup.event_control
cgroup.procs
cpuacct.stat
cpuacct.usage
cpuacct.usage_percpu
notify_on_release
release_agent
tasks
uid
uid_10006
uid_10014
uid_1037

我正在运行 Windows 8、Android Studio 2.2 和 Gradle 2.10

更新 我尝试了 Andrey 的建议:

task runTests {
    doLast {
        def testOutput = 'adb shell ls acct'.execute([], project.rootDir).text.trim()
        setProperty("archivesBaseName", testOutput)
        println testOutput
    }
}

但这会打印输出的最后一行,即

uid_1037

【问题讨论】:

    标签: android android-studio gradle adb


    【解决方案1】:

    我使用以下代码来捕获和使用命令输出:

    def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
    
    android {
        compileSdkVersion 23
        buildToolsVersion "24.0.1"
        ...
        defaultConfig {
            applicationId "ru.****.***"
            minSdkVersion 21
            targetSdkVersion 23
            versionCode 2
            versionName "0.2"
            setProperty("archivesBaseName", APK_NAME + "-" + versionName + "." + versionCode + "-" + "${gitSha}")
        }
        ...
    }
    

    我认为adb shell可以用同样的方式调用。

    【讨论】:

    • 感谢@andrey-kopeyko 的建议。我试过这个,但除了最后一行输出之外,它会为所有内容打印空行。在“adb shell ls acct”的情况下,它会打印 12 个空白行,后跟“uid_1037”
    • 你试过什么代码?请写下具体的代码和输出。
    • 您不需要用cmd /c 包装您的命令 - 尝试直接执行adb,例如adb shell ls -l /
    • Andrey,我更新了帖子以显示我使用的命令和输出。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-01
    • 1970-01-01
    • 2014-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多