首先說我對 Kotlin 完全陌生,但現在是我開始理解這件事的時候了。
我有一個在 powershell 中運行的命令。
kubectl get pods -o jsonpath='{range .items[*]}{.spec.containers[].image}{\"\n\"}{end}'
我想創建一個 kotlin 腳本來運行該命令,然后使用 kotlin 中的某些內容(如 Java 字串標記器)將 kotlin 中的輸出決議為字串。
在這個階段,我使用 kotlin 腳本并有一個基本的 hello world 作業,如下所示。我在問題中列出這一點的唯一原因是 bc 我想堅持使用一個簡單的 kotlin 腳本并想說明這一點:
println("Called with args:")
args.forEach {
println("- $it")
}
RUN AND OUTPUT OF SCRIPT
kotlinc -script .\helloScript.kts hello
Called with args:
- hello
有人可以幫助我如何最好地在 Kotlin 腳本中編碼嗎?我已經做了一些研究,但我發現很難找到適合我所追求的正確例子。
謝謝!
uj5u.com熱心網友回復:
我沒有測驗它,但沿著這個(在 JVM 上):
val command = arrayOf(
"kubectl",
"get",
"pods",
"-o",
"jsonpath='{range .items[*]}{.spec.containers[].image}{\"\n\"}{end}'"
)
Runtime.getRuntime()
.exec(command)
.waitFor() // this line only if necessary
或者如果有回傳值(在這種情況下為一行):
val text = Runtime.getRuntime()
.exec(command)
.inputStream
.bufferedReader()
.readLine()
.orEmpty()
.trim()
uj5u.com熱心網友回復:
我已經在這里接受了一個答案,因為它對我有幫助,但只是為了完整起見,在這里玩了一些樂趣之后,我最終得到的結果是,當我完成它時,它正在起作用。謝謝大家
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.nio.charset.Charset
import java.util.ArrayList
import java.util.HashMap
import kotlin.text.Charsets.UTF_8
val command = "kubectl get pods"
execLocal(command)
fun execLocal(command: String): String {
try {
val commands = ArrayList<String>()
commands.add("powershell.exe")
commands.add("-Command")
commands.add(command)
val pb = ProcessBuilder(commands)
println("Running: " pb.command())
val process = pb.start()
val result = collectOutput(process.inputStream)
if (process.waitFor() != 0) {
println("Failed to execute command: " pb.command())
println("Result: " result)
throw RuntimeException()
} else {
println("stdout: " result)
}
return result
} catch (e: IOException) {
throw RuntimeException(e)
} catch (e: InterruptedException) {
throw RuntimeException(e)
}
}
fun collectOutput(inputStream: InputStream): String {
val out = StringBuilder()
val buf: BufferedReader = inputStream.bufferedReader(UTF_8)
var line: String? = buf.readLine()
do {
if (line != null) {
out.append(line).append("\n")
}
line = buf.readLine()
} while (line != null)
return out.toString()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362396.html
標籤:科特林
