1

I am able to execute shell commands (that has a return value) in Kotlin [Android] using the following lines of code:

  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()
    }

The above lines of code are capable of running the shell command but the output of the command should be something as follows if the command was written in the add shell:

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

How can I get these above values returned in the getFrequencyLevelsCPU0() function in Kotlin after executing the shell command?

2 Answers 2

2

Since you have a java.lang.Process, you can use its getInputStream() (in Kotlin it can be shortened to just inputStream) (see JavaDoc here) to read the output, for example:

val output = process.inputStream.bufferedReader().lineSequence().joinToString("\n")
Sign up to request clarification or add additional context in comments.

Comments

1

There is a kotlin library for easy run external command

Add this gradle dependency:

implementation("com.sealwu:kscript-tools:1.0.2")

And can run comamnd like this:

"cd ~ && ls".runCommand()

Output:

Applications   Downloads      MavenDep       Pictures       iOSProjects
Desktop        IdeaProjects   Movies         Public         scripts
Documents      Library        Music          StudioProjects

Also you can get the output of command line by using evalBash

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)

Output:

Fri Aug 19 21:59:56 CEST 2022
2022

More Info: https://github.com/wuseal/Kscript-Tools

2 Comments

Tried it in Kscript and got error: unresolved reference: runCommand Details: Kotlin 1.7 and Macos 12.4. @file:DependsOn("com.sealwu:kscript-tools:1.0.2") looks like it works. I notice the github project has no unit tests. Unit test would help me know if I need to do an import.
Hello @devdanke in the latest kscript it is indeed requiring importing root function while there is no need in normal kotlin code and kscipt 3.1.0 more info refer: github.com/kscripting/kscript/issues/377

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.