Java/Kotlin使用可见的命令提示符运行Runtime.getRuntime().exec()



在我的windows系统上,我想使用Runtime.getRuntime().exec(command)用python脚本启动一个子进程,并打开命令提示符终端,这样用户就可以看到进程在工作。我的命令类似于:

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

我知道有一种替代方法可以通过以下方式将命令提示符的内容打印回原始终端:

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

只是想知道是否还有其他我还没有看到的选择。

我认为您应该使用ProcessBuilder的重定向:

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

这个例子和你的行为相同。

相关内容

最新更新