Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Run python script from java as subprocess

I'm trying to execute python code (live from the console, not just opening a single file).

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");

I tried this code, but after trying to push the following expressions 1 and 2*2, I don't get a response (evaluation of my expressions).

Does anyone know what the issue is?

Answer*

Draft saved
Draft discarded

Required fields are marked with *

Cancel
13
  • 1
    I was to have a long running python terminal, that I can at any point run commands on Commented Feb 11, 2020 at 20:18
  • 1
    If I wanted this solution, I could simply put the code in a python file, and execute that "python mycode.py" Commented Feb 11, 2020 at 20:18
  • 1
    Then I would suggest you use Jython or one of the other integration packages (rolling your own REPL while trying to integrate with CPython is not my idea of fun). Commented Feb 11, 2020 at 20:20
  • 1
    I've checked out jython, but its a big dependency, and also doesn't make use of the system python version Commented Feb 11, 2020 at 20:22
  • 2
    Thanks for the fix. Question: what's wrong with writing on the main thread? Commented Feb 11, 2020 at 21:18

default