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

标签 exec kotlin

我想从 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/

相关文章:

node.js - 从 Node JS 在其自己的控制台窗口中打开 Windows child_process exec

android - kotlin 中的 requireActivity() 和 requireContext()

class - 子类的Kotlin变量初始化对于将值初始化为0的行为很奇怪

android - Kotlin - 如何在 Telegram 应用程序中打开 Telegram 群组的链接

ruby-on-rails - 在每个场景之前在 cucumber 中运行 exec 'rake db:drop db:create db:migrate db:seed'

java - 无法运行程序 "..../abc.exe": error=13, 权限被拒绝

inheritance - 在列表上下文中使用kotlin类扩展时,解析父类的值而不是子类的值

firebase - 为什么我的Firebase代码中的 “object”用红色下划线?

c - 为什么 more 命令不使用 stdin 来读取输入?

c - C 中的后台进程(守护进程)不是 execvp() -ing