Skip to content

Instantly share code, notes, and snippets.

@pfichtner
Last active March 24, 2019 16:04
Show Gist options
  • Select an option

  • Save pfichtner/a27b714a9bd43b0e361fdc9d4fc396ab to your computer and use it in GitHub Desktop.

Select an option

Save pfichtner/a27b714a9bd43b0e361fdc9d4fc396ab to your computer and use it in GitHub Desktop.
import static java.util.Arrays.asList;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class PythonBuffering {
// run python in buffering mode (pyhon default) or unbuffered using "-u"
static boolean runWithMinusU = false;
// call sys.stdout.flush() in py code
static boolean forceFlush = false;
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(createProcess().getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(new Date() + " " + line);
}
}
private static Process createProcess() throws IOException, FileNotFoundException {
List<String> pyArgs = new ArrayList<>(asList("python", createPyFile().getAbsolutePath()));
if (runWithMinusU) {
pyArgs.add(1, "-u");
}
return new ProcessBuilder().command(pyArgs).redirectErrorStream(true).start();
}
private static File createPyFile() throws IOException, FileNotFoundException {
File pyCode = File.createTempFile("buffering-showcase-", ".py");
pyCode.deleteOnExit();
Files.write(pyCode.toPath(), pyCode());
return pyCode;
}
private static List<String> pyCode() {
List<String> lines = new ArrayList<>();
lines.add("#!/usr/bin/python");
lines.add("");
lines.add("import sys");
lines.add("import time");
lines.add("");
lines.add("x = 1");
lines.add("while True:");
lines.add(" print(x)");
if (forceFlush) {
lines.add(" sys.stdout.flush()");
}
lines.add(" time.sleep(0.01)");
lines.add(" x += 1");
lines.add("");
return lines;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment