我想从 Kotlin 代码中调用一个外部命令。
- 在 C/Perl 中,我会使用
system()
函数。 - 在 Python 中,我会使用 subprocess 模块。
- 在 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
}
}
关于exec - 如何从 Kotlin 代码中调用外部命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35421699/