Executing a Jython function from Java

P

ProgDario

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
 
P

ProgDario

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()) +
"]===========");
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top