我有一个函数,它使用以下代码将字符串作为命令执行:
fun String.runAsCommand() : String {
val process = Runtime.getRuntime().exec(this)
if (!process.waitFor(60, TimeUnit.SECONDS)) {
process.destroy()
throw RuntimeException("execution timed out: $this")
}
if (process.exitValue() != 0) {
throw RuntimeException("execution failed with code ${process.exitValue()}: $this")
}
return process.inputStream.bufferedReader().readText()
}但是,这段代码会在完成所有操作后输出命令输出。但是这个过程实际上是一个很长的过程,最多需要40秒,并逐渐将状态输出到控制台。如何使用某种侦听器结构截取这些echo的/控制台日志?
发布于 2020-05-01 23:57:10
标准方法是使用ProcessBuilder,并启动另一个线程来读取进程的stdout (这是您的输入)。
我不确定这是否是最好的方法,但我想出了一些代码来做一些非常类似的事情。(在我的例子中,进程写到了它的stdout和stderr,所以我需要读取它们--但在进程结束之前我不需要看到它们。我还需要返回进程的退出状态以及这两个退出状态,并处理超时。我不需要向进程的stdin发送任何东西;如果需要,就必须扩展它。)
/**
* Runs a system command and captures its output (and stderr).
*
* @param command The program name and any arguments.
* @param workingDir The working directory of the process, or `null` for the same as this process.
* @param timeoutSecs Maximum time to wait for it to finish, in seconds. (Default is 5 mins.)
* @param throwOnFailure Whether to throw a [ProcessFailedException] if it returns a non-zero exit value.
* @throws IndexOutOfBoundsException if the command is empty.
* @throws SecurityException if a security manager prevented creation of the process or a redirection.
* @throws UnsupportedOperationException if the OS doesn't support process creation.
* @throws IOException if an I/O error occurs.
* @throws ProcessTimedOutException if the timeout expires before the process finishes.
* @throws ProcessFailedException if the process returns a non-zero exit status.
*/
fun runProcess(vararg command: String, workingDir: File? = null, timeoutSecs: Long = 300,
throwOnFailure: Boolean = true): ProcessResult {
val proc = ProcessBuilder(*command)
.directory(workingDir)
.start()
// Must read both output and error, else it can deadlock.
class StreamReader(val stream: InputStream, val result: StringBuilder) : Runnable {
override fun run() = stream.bufferedReader().use { s ->
while (true)
result.appendln(s.readLine() ?: break)
}
}
val output = StringBuilder()
Thread(StreamReader(proc.inputStream, output)).start()
val error = StringBuilder()
Thread(StreamReader(proc.errorStream, error)).start()
val exited = proc.waitFor(timeoutSecs, TimeUnit.SECONDS)
if (!exited)
throw ProcessTimedOutException("${command[0]} timed out!", timeoutSecs, output.toString(), error.toString())
val exitValue = proc.exitValue()
if (exitValue != 0 && throwOnFailure)
throw ProcessFailedException("${command[0]} failed: $error", exitValue, output.toString(), error.toString())
return ProcessResult(exitValue, output.toString(), error.toString())
}
/** Thrown if a process doesn't finish within the timeout period. */
class ProcessTimedOutException(msg: String, val timeoutSecs: Long, val output: String, val error: String) : Exception(msg)
/** Thrown if a process returns a non-zero code. */
class ProcessFailedException(msg: String, val exitValue: Int, val output: String, val error: String) : Exception(msg)
/** Returned if a process completes. */
class ProcessResult(val exitValue: Int, val output: String, val error: String)https://stackoverflow.com/questions/61544384
复制相似问题