如何从Kotlin代码中调用外部命令?

我想从Kotlin代码中调用外部命令。 在C / Perl中,我会使用system()函数; 在Python中,我会使用子进程模块; 在Go中,我将使用os / exec; 等等。但是,如何在Kotlin中做到这一点?

通过脱壳来运行git diff的示例:

"git diff".runCommand(gitRepoDir)

下面是runCommand扩展函数的两个实现:

1.重定向到stdout / stderr

这将来自子进程的输出连接到常规标准输出和标准错误:

 fun String.runCommand(workingDir: File) { ProcessBuilder(*split(" ").toTypedArray()) .directory(workingDir) .redirectOutput(Redirect.INHERIT) .redirectError(Redirect.INHERIT) .start() .waitFor(60, TimeUnit.MINUTES) } 

2.以字符串形式捕获输出

重定向到Redirect.PIPE的替代实现允许您捕获String输出:

 fun String.runCommand(workingDir: File): String? { try { val parts = this.split("\\s".toRegex()) val proc = ProcessBuilder(*parts.toTypedArray()) .directory(workingDir) .redirectOutput(ProcessBuilder.Redirect.PIPE) .redirectError(ProcessBuilder.Redirect.PIPE) .start() proc.waitFor(60, TimeUnit.MINUTES) return proc.inputStream.bufferedReader().readText() } catch(e: IOException) { e.printStackTrace() return null } } 

如果您在JVM上运行,则可以使用Java Runtime exec方法 。 例如

 Runtime.getRuntime().exec("mycommand.sh") 

您将需要安全权限来执行命令。