3

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.

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer. I can replicate the same behaviour as above but there's no visible command prompt/terminal that appears to display the output. I'm fine with re-directing, but is there a way I can force open the terminal?
@PeptideWitch yes. Try replacing cmd /C dir with cmd /C start dir
this worked for me, windows 10 kotlin ProcessBuilder("cmd /C start dir".split(" ")) .redirectOutput(ProcessBuilder.Redirect.INHERIT) .start() .waitFor()

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.