Skip to content

Instantly share code, notes, and snippets.

@ajoyoommen
Last active February 12, 2019 06:25
Show Gist options
  • Save ajoyoommen/f68a404b1039beb5e2fe5543439506e0 to your computer and use it in GitHub Desktop.
Save ajoyoommen/f68a404b1039beb5e2fe5543439506e0 to your computer and use it in GitHub Desktop.
Run a python application from within Java. These methods use Jython (which does not support python 3) and Runtime
import json
class Data:
def fetch(self):
return json.dumps({
'name': 'scraper',
'results': []
})
def fetch():
data = Data()
return data.fetch()
if __name__ == '__main__':
print(fetch())
print("Success")
package com.project.pythonIntegration;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.Properties;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class Launcher {
public static void main(String[] args) {
integrationWithJython();
}
public static void integrationWithJython() {
// WIP
PythonInterpreter interpreter = null;
Properties p = new Properties();
p.setProperty("python.import.site", "false");
interpreter.initialize(System.getProperties(), p, new String[] {});
interpreter = new PythonInterpreter();
interpreter.exec("results = fetch()");
PyObject results = interpreter.get("results");
System.out.println(results);
}
public static void integrationWithPython() {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec("python C:\\Users\\user.name\\eclipse-workspace\\PythonIntegration\\app.py");
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while((line = bfr.readLine()) != null)
{
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment