최근 프로젝트에서 코틀린 애플리케이션에서 동적으로 파이썬 스크립트를 실행해야 하는 요구사항이 있었고 구현 과정에서 예상치 못한 여러 문제를 만났다
1. 코틀린에서 파이썬 실행하기
처음에는 단순히 코틀린의 ProcessBuilder를 사용해 파이썬 스크립트를 실행하고 그 결과를 받아오는 방식을 선택했다. 파이썬 프로그램을 실행하고 출력을 읽어와서 활용하려고 했다.
import java.io.BufferedReader
import java.io.InputStreamReader
// 예시 코드
fun executePythonScript(scriptPath: String): String {
val processBuilder = ProcessBuilder("python3", scriptPath)
processBuilder.redirectErrorStream(true) // stdout과 stderr를 합침
val process = processBuilder.start()
val output = StringBuilder()
BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
var line: String?
while (reader.readLine().also { line = it } != null) {
output.append(line).append("\n")
}
}
process.waitFor()
return output.toString()
}
fun main() {
val result = executePythonScript("path/to/your_script.py")
println("Python script output:\n$result")
}
2. 부가적인 print 출력 처리
이 코드로 실행하면 예상대로 결과는 출력되었으나 운영체제에 따라 출력이 다르게 나와서 이상한 값이 포함되는 문제가 있었다. 결과를 파싱하는 데 어려움이 있어. 마지막 줄만 추출하는 방식으로 결과의 모든 줄을 읽어오는 대신,마지막 줄만 사용하는 방법으로 문제를 해결했다.
fun executePythonScript(scriptPath: String): String {
val processBuilder = ProcessBuilder("python3", scriptPath)
processBuilder.redirectErrorStream(true)
val process = processBuilder.start()
val output = BufferedReader(InputStreamReader(process.inputStream)).lines()
val lastLine = output.reduce { _, current -> current }.orElse(null)
process.waitFor()
return lastLine ?: ""
}
3. 운영체제별 파이썬 실행 경로 차이
파이썬 실행 경로가 운영체제에 따라 달라
이를 해결하기 위해 코틀린에서 실행 중인 운영체제를 확인하고, 각 운영체제에 맞는 파이썬 경로를 설정하도록 했다.
fun getPythonCommand(): String {
val os = System.getProperty("os.name").toLowerCase()
return when {
os.contains("win") -> "python"
os.contains("nix") || os.contains("nux") || os.contains("mac") -> "python3"
else -> throw UnsupportedOperationException("Unsupported OS: $os")
}
}
'트러블슈팅 > 회사' 카테고리의 다른 글
spring batch reader (0) | 2025.01.31 |
---|---|
modbus 데이터 가져오기 (1) | 2024.12.28 |
Modbus protocol (2) | 2024.12.28 |
loki 적용하기 (0) | 2024.11.04 |
로그 수집 및 에러 알림 만들기 (0) | 2024.10.18 |