Estou tentando executar código python (ao vivo a partir do console, não apenas abrir um único arquivo).
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");
Eu tentei este código, mas depois de tentar empurrar as seguintes expressões 1
e 2*2
, eu não obter uma resposta (avaliação das minhas expressões).
Alguém sabe qual é o problema?
Seu python
código não aparecem para imprimir qualquer coisa, e lidar com múltiplos threads para ler e escrever para um outro processo é um tema complicado; Felizmente, a funcionalidade é embutido. Você poderia fazer
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();
}
que resultados
4
e termina. Por menos trivial integração Python e Java, eu sugiro fortemente que você olha aqui . Quanto ao seu código existente, você nunca exit()
python e você nunca flush()
o seu PrintWriter
. E você escrever sobre o main
fio. E você precisa passar -i
para python, ou não vai assumir stdin é um console. Alterar o código para
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();
Parece funcionar corretamente.