Welcome to the new platform of Programmers Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use it's exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.
Invoking python script from Java
I am working on a Java program for use at work that is coming along nicely. It is used to analyze log files. For one particular type of log files, we already have a nice python script that will generate all sorts of statistical information about run lengths, the top 10 SQL statements used, the number of rows aggregated and deleted from each table, etc. In a sense -- it's really slick!
Rather than reinvent the wheel I just planned on including it with the Java program that I'm working on right now, and invoking it whenever that particular log needs to be analyzed. Is there a simple way to do this? I have been looking into jython but so far all of the examples that I have found and research I have done suggests that jython is used to invoke Java code from within a python script. Is there a way to do precisely the opposite? I found some information about jythonc but I thought I read somewhere that it was deprecated and no longer supported.
Actually, I know that there is a way to invoke python from within Java and I have done it:
public class Foo
public static void main(String args)
Runtime r = Runtime.getRuntime();
Process p = r.exec("python foo.py");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
catch (Exception e)
String cause = e.getMessage();
if (cause.equals("python: not found"))
System.out.println("No python interpreter found.");
It works perfectly:
$ cat foo.py
$ java Foo
$ echo "print "ASDF"" >> foo.py
$ cat foo.py
$ java Foo
The only problem with this method is that it requires the user to have a python interpreter installed on their system (and in the PATH). Is there some way that I can just include a jar file with the final code and then just call a Java class inside of that jar which will interpret and execute the python script for me? I think jython might be able to do this but I'm not sure.
What about jythonc? Should I be using that? I was able to use it to produce a jar file which seems to be what I want...but every class it compiled has a hard-coded path in it the python script. That's not very portable! I also haven't figured out exactly how to invoke my script yet.
Seems like I just want to include an entire jar file containing jython (there is an option in the installation to make it a jar file). That sounds like what I should be doing -- but I don't know how to use it to invoke my python script from inside of my Java code. Can anyone tell me how to do that?