Skip to content

Instantly share code, notes, and snippets.

@DrPlantabyte
Last active February 18, 2016 19:29
Show Gist options
  • Save DrPlantabyte/6872a76c6f0376b89565 to your computer and use it in GitHub Desktop.
Save DrPlantabyte/6872a76c6f0376b89565 to your computer and use it in GitHub Desktop.
Run scientific python scripts in java app via process spawning
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
/**
*
* @author CCHall <a href="mailto:hallch20@msu.edu">hallch20@msu.edu</a>
*/
public class NativePythonTest {
public static void main(String[] params){
try{
System.out.println(System.getenv().toString().replace(", ", "\n"));
File executionDir = new File(".");
String plotFilename = "plot.png";
String pythonExec = executionDir.getAbsolutePath()+File.separator+"Anaconda3\\python.exe";
String pythonHome = executionDir.getAbsolutePath()+File.separator+"Anaconda3";
String pythonLibs = executionDir.getAbsolutePath()+File.separator+"Anaconda3\\Lib\\site-packages";
String script = "print('Starting...')\n" +
"from scipy import special, optimize\n" +
"import numpy\n" +
"import matplotlib.pyplot\n" +
"f = lambda x: -special.jv(3, x)\n" +
"sol = optimize.minimize(f, 1.0)\n" +
"x = numpy.linspace(0, 10, 5000)\n" +
"x\n" +
"matplotlib.pyplot.plot(x, special.jv(3, x), '-', sol.x, -sol.fun, 'o')\n" +
"matplotlib.pyplot.savefig('"+plotFilename+"', dpi=96)\n" +
"print('...Done')\n" +
"exit()";
ProcessBuilder pb = new ProcessBuilder();
pb.environment().put("PYTHONHOME",pythonHome);
pb.environment().put("PYTHONPATH",pythonLibs);
pb.environment().put("PATH", System.getenv().get("Path")); // Java on windows is less picky about capitalization than Python
pb.command(pythonExec, "-c", script);
pb.directory(executionDir);
Process p = pb.start();
// BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
// stdin.write(script);
BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
Thread listener = new Thread(()->{
stdout.lines().forEach((String line)->System.out.println(line));
stderr.lines().forEach((String line)->System.err.println(line));
});
listener.setDaemon(true);
listener.start();
p.waitFor();
Path outputFile = Paths.get(executionDir.getPath(),plotFilename);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(ImageIO.read(outputFile.toFile()))));
//Thread.sleep(10000);
Files.delete(outputFile);
System.exit(0);
}catch(Exception ex){
ex.printStackTrace(System.err);
}
}
}
@DrPlantabyte
Copy link
Author

Worked with SciPy compiled libraries. Just install SciPy (Anaconda3 package in this case) and distribute the installation folder with the java app and properly set the PATH, PYTHONPATH, and PYTHONHOME environment variables for the sub-process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment