0

I have a java program that runs a python exe. Since the script returns a progress float using stdout, I would like to read these status messages immediately when they are printed.

Here is the code I tried:

public void run()
{
    // Create new process builder
    ProcessBuilder mProcBldr = new ProcessBuilder(mArgs.toArray(new String[0]));

    // Set it to working directory of the extracted resource
    mProcBldr.directory(new File(mPyExe.getPath()));

    // Start the process
    mProcess = mProcBldr.start();
    mStdIn = new BufferedReader(new InputStreamReader(mProcess.getInputStream()), 128);
    mStdErr = new BufferedReader(new InputStreamReader(mProcess.getErrorStream()), 128);
}
public float getProgress()
{
    float progress = 0.0f;
    try
    {
        String s;
        while ((s = mStdIn.readLine()) != null)
        {
            System.out.println(s);
        }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

    return progress;
}

GetProgress() is called in a loop until the process exits.

python.run();
while(!python.isFinished())
{
    System.out.println(python.getProgress());
}

It sort of works, but it is very "buffered". It prints all the way up to 30% then waits for a second, then it prints to 60%... waits for a second... etc...

Is there any way to read the printed lines immediately so that the progress updates smoothly?

Best Regards

teepers
  • 22
  • 4
  • Your problem is not the Java reading but the Python writing; dupe https://stackoverflow.com/questions/107705/disable-output-buffering https://stackoverflow.com/questions/230751/how-to-flush-output-of-print-function – dave_thompson_085 Aug 21 '20 at 08:17
  • I just tried this and it worked. Makes so much sense now haha. – teepers Aug 21 '20 at 13:46

0 Answers0