首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Kotlin中执行shell命令并从shell [Android]中获取返回值

如何在Kotlin中执行shell命令并从shell [Android]中获取返回值
EN

Stack Overflow用户
提问于 2022-07-12 21:53:45
回答 2查看 522关注 0票数 0

我能够使用以下代码行在Kotlin Android中执行shell命令(该命令具有返回值):

代码语言:javascript
运行
复制
  fun getFrequencyLevelsCPU0(): Unit {
        val process: java.lang.Process = java.lang.Runtime.getRuntime().exec("su -c cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_available_frequencies")
        process.waitFor()
    }

上面的代码行可以运行shell命令,但是如果命令是在add中编写的,则命令的输出应该如下所示:

500000 851000 984000 1106000 1277000 1426000 1582000 1745000 1826000 2048000 2188000 2252000 2401000 2507000 2630000 2704000 2802000

在执行shell命令之后,如何获得Kotlin中的getFrequencyLevelsCPU0()函数中返回的上述值?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-07-12 23:29:05

由于您有一个java.lang.Process,所以可以使用它的getInputStream() (在Kotlin中可以将它缩短为inputStream) (例如,读取输出的在这里见JavaDoc):

代码语言:javascript
运行
复制
val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n")
票数 1
EN

Stack Overflow用户

发布于 2022-08-20 12:30:32

有一个kotlin库可以方便地运行外部命令。

添加这个等级依赖关系:

代码语言:javascript
运行
复制
implementation("com.sealwu:kscript-tools:1.0.2")

可以像这样运行:

代码语言:javascript
运行
复制
"cd ~ && ls".runCommand()

输出:

代码语言:javascript
运行
复制
Applications   Downloads      MavenDep       Pictures       iOSProjects
Desktop        IdeaProjects   Movies         Public         scripts
Documents      Library        Music          StudioProjects

此外,还可以使用evalBash获取命令行的输出。

代码语言:javascript
运行
复制
val date = "date".evalBash().getOrThrow()  //execute shell command `date` and get the command's output and set the content to date variable
println(date) //This will print Fri Aug 19 21:59:56 CEST 2022 on console
val year = date.substringAfterLast(" ") // will get 2022 and assign to year
println(year)

输出:

代码语言:javascript
运行
复制
Fri Aug 19 21:59:56 CEST 2022
2022

更多信息:https://github.com/wuseal/Kscript-Tools

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72958779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档