Executing a Jython function from Java

ProgDario dario at fga-software.com
Fri Sep 5 10:36:25 EDT 2003


dario at fga-software.com (ProgDario) wrote in message news:<67a857cc.0309050122.644ea7ee at posting.google.com>...
> Hello,
> 
> in the site I found a lot of complicated examples, but I can't find
> the simple one I'm looking for.
> 
> The problem is:
> 
> I have 1 jython file (script1.py) with a function named 'calculate',
> and a java file (run.java).
> 
> I'd like to call the jython function from the java class recursively.
> <<====<<
> 
> I think it can be possible to get a PyFunction object that rapresents
> the function, and then call the function from the already evaluated
> object, so I don't need to re-evaluate it every loop.
> 
> My code is something like this:
> 
> PythonInterpreter interp = new PythonInterpreter();
> interp.execfile('script1.py');
> for (int i = 0; i < 1000; i++) {
> interp.eval("calculate(8)");
> }
> 
> Thanks in advance,
> 
> Dario

I searched the web for a long time, and finally Jeff Emanuel emailed
me and solved the problem.

That's the code, any advice is apreciated:

import java.io.*;
import java.util.*;
import java.text.*;

import org.python.util.PythonInterpreter;
import org.python.core.*;

public class Calculate {
  public static void main(String[] args){
    PythonInterpreter interp = new PythonInterpreter();
    interp.execfile("script1.py");
    PyFunction func =
(PyFunction)interp.get("calculate",PyFunction.class);
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh.mm.ss");
    System.out.println("======[" + sdf.format(new Date()) +
"]===========");
    for (int i=1 ; i<10000 ; ++i) {
      // Assuming calculate takes a float argument.
      func.__call__(new PyFloat(i));
			//interp.eval("calculate(" + i + ")");
    }
    System.out.println("======[" + sdf.format(new Date()) +
"]===========");
  }
}




More information about the Python-list mailing list