Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java/Kotlin run Runtime.getRuntime().exec() with visible command prompt

On my windows system, I would like to use Runtime.getRuntime().exec(command) to launch a subprocess with a python script and have the command prompt terminal open so users can see the process working. My command is something like:

val command = "cmd /c python ~path_to_file~ ~args~"

I'm aware there's an alternate method to print the contents of the command prompt back into the original terminal via something like:

import java.util.Scanner
fun main(args: Array<String>) {
    val proc = Runtime.getRuntime().exec("cmd /C dir") 
    Scanner(proc.inputStream).use {
        while (it.hasNextLine()) println(it.nextLine())
    }
}

Just wondering if there's another option I haven't seen yet.

like image 955
PeptideWitch Avatar asked Dec 18 '25 07:12

PeptideWitch


1 Answers

I think you should use ProcessBuilder's redirecting:

fun main() {
    ProcessBuilder("cmd", "/C", "dir")
        .redirectOutput(ProcessBuilder.Redirect.INHERIT)
        .start()
        .waitFor()
}

This example has same behavior as yours.

like image 86
Commander Tvis Avatar answered Dec 20 '25 20:12

Commander Tvis