Tobiq :
나는 (단지 하나의 파일을 열 수 없습니다, 콘솔에서 라이브) 파이썬 코드를 실행하기 위해 노력하고있어.
ProcessBuilder builder = new ProcessBuilder("python");
Process process = builder.start();
new Thread(() -> {
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
String line;
final BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
// Ignore line, or do something with it
while (true) try {
if ((line = reader.readLine()) == null) break;
else System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
final PrintWriter writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream()));
writer.println("1");
writer.println("2 * 2");
이 코드를했는데, 다음과 같은 식을 밀어 시도 후 1
와 2*2
내가 응답 (내 표현의 평가)를 얻을하지 않습니다.
사람이 문제가 무엇인지 알고 있나요?
엘리엇의 신선한 :
귀하의 python
코드는 무엇을 인쇄하고, 다중 스레드를 처리하는 읽고 다른 프로세스에 대한 쓰기가 까다로운 주제 표시되지 않습니다; 다행히, 기능이 내장되어있다. 당신은 할 수
ProcessBuilder builder = new ProcessBuilder("/usr/bin/env", "python",
"-c", "print(2*2); exit()");
builder.inheritIO();
try {
Process process = builder.start();
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
}
어떤 출력
4
및 종료. 적은 사소한 파이썬과 자바 통합을 위해, 나는 강하게 당신이 보는 제안 여기 . 기존 코드, 당신이 결코에 관해서는 exit()
파이썬과 결코 flush()
당신 PrintWriter
. 그리고 당신은에 쓰기 main
스레드. 그리고 당신은 통과해야 -i
파이썬으로, 또는 표준 입력지지 않습니다 콘솔입니다. 에 코드 변경
ProcessBuilder builder = new ProcessBuilder("/usr/bin/env", "python", "-i");
Process process = builder.start();
new Thread(() -> {
String line;
final BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
// Ignore line, or do something with it
while (true)
try {
if ((line = reader.readLine()) == null)
break;
else
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}).start();
new Thread(() -> {
final PrintWriter writer = new PrintWriter(
new OutputStreamWriter(process.getOutputStream()));
writer.println("1");
writer.println("2 * 2");
writer.println("exit()");
writer.flush();
}).start();
제대로 작동하는 것 같다.