2016-12-05 153 views
0

A previous post显示如何获得使用gradle执行的shell命令的输出。但是,当我尝试将此应用于“adb shell”命令时,它会打印空白行。例如,此脚本:如何使用gradle获得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中和摇篮2.10

更新 我想安德烈的建议:

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

但是此打印输出的最后一行,即

uid_1037 

回答

0

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

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可以以相同的方式来调用。

+0

感谢您的建议,@ andrey-kopeyko。我试过这个,但是除了输出的最后一行以外,它都会打印空行。在'adb shell ls acct'的情况下,它会打印12个空行,后跟“uid_1037” – Martin

+0

你试过了什么代码?请写下特定的代码和输出。 –

+0

你不需要用'cmd/c'来包装你的命令 - 尝试直接执行'adb',就像'adb shell ls -l /' –