Kotlin本机执行命令并获取输出

时间:2019-07-20 10:27:36

标签: terminal posix kotlin-native

我想知道kotlin本机中是否可以通过posix调用命令并接收其终端输出。例如,我想使“ git diff”命令正常工作,而不必创建一个临时文件,将输出写入该文件,然后从该文件中读取。

因此,我仅发现需要ProcessBuilder的解决方案,由于它是Java库,因此在kotlin-native上不可用。

3 个答案:

答案 0 :(得分:1)

我找到了我想使用的一段有效代码,因此我将其发布在这里供以后的观看者使用!

fun executeCommand(command: String): String{
    val fp: CPointer<FILE>? = popen(command, "r")
    val buffer = ByteArray(4096)
    val returnString = StringBuilder()

    /* Open the command for reading. */
    if (fp == NULL) {
        printf("Failed to run command\n" )
        exit(1)
    }

    /* Read the output a line at a time - output it. */
    var scan = fgets(buffer.refTo(0), buffer.size, fp)
    if(scan != null) {
        while (scan != NULL) {
            returnString.append(scan!!.toKString())
            scan = fgets(buffer.refTo(0), buffer.size, fp)
        }
    }
    /* close */
    pclose(fp)
    return returnString.trim().toString()
}

答案 1 :(得分:1)

这是mg-lolenstine发布的Kotlin Native的exec命令的改进版本,它使用命令stderr引发异常,而不是仅仅返回exit(1)(本身并不总是令人满意的行为),现在也进行了修剪可选

import kotlinx.cinterop.*
import platform.posix.*

fun executeCommand(
    command: String,
    trim: Boolean = true,
    redirectStderr: Boolean = true
): String {
    val commandToExecute = if (redirectStderr) "$command 2>&1" else command
    val fp = popen(commandToExecute, "r") ?: error("Failed to run command: $command")

    val stdout = buildString {
        val buffer = ByteArray(4096)
        while (true) {
            val input = fgets(buffer.refTo(0), buffer.size, fp) ?: break
            append(input.toKString())
        }
    }

    val status = pclose(fp)
    if (status != 0) {
        error("Command `$command` failed with status $status${if (redirectStderr) ": $stdout" else ""}")
    }

    return if (trim) stdout.trim() else stdout
}

答案 2 :(得分:1)

我使用上面的答案来创建一个运行任意本地进程/命令的工作 gradle kotlin native/jvm 多平台多项目:

这是我的结果:

https://github.com/hoffipublic/minimal_kotlin_multiplatform

import kotlinx.cinterop.refTo
import kotlinx.cinterop.toKString
import platform.posix.fgets
import platform.posix.pclose
import platform.posix.popen

actual object MppProcess : IMppProcess {
    actual override fun executeCommand(
        command: String,
        redirectStderr: Boolean
    ): String? {
        val commandToExecute = if (redirectStderr) "$command 2>&1" else command
        val fp = popen(commandToExecute, "r") ?: error("Failed to run command: $command")

        val stdout = buildString {
            val buffer = ByteArray(4096)
            while (true) {
                val input = fgets(buffer.refTo(0), buffer.size, fp) ?: break
                append(input.toKString())
            }
        }

        val status = pclose(fp)
        if (status != 0) {
            error("Command `$command` failed with status $status${if (redirectStderr) ": $stdout" else ""}")
        }

        return stdout
    }
}

在jvm上

import java.util.concurrent.TimeUnit

actual object MppProcess : IMppProcess {
    actual override fun executeCommand(
        command: String,
        redirectStderr: Boolean
    ): String? {
        return runCatching {
            ProcessBuilder(command.split(Regex("(?<!(\"|').{0,255}) | (?!.*\\1.*)")))
                //.directory(workingDir)
                .redirectOutput(ProcessBuilder.Redirect.PIPE)
                .apply { if (redirectStderr) this.redirectError(ProcessBuilder.Redirect.PIPE) }
                .start().apply { waitFor(60L, TimeUnit.SECONDS) }
                .inputStream.bufferedReader().readText()
        }.onFailure { it.printStackTrace() }.getOrNull()
    }
}