Jython: Python for the Java Platform - http://www.jython.org/index.html
You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.
If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.
A simple example from the top of my head - but should work I hope: (no error checking done for brevity)
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);
As of 2021, Jython does not support Python 3.x
Answer from Voo on Stack OverflowJython: Python for the Java Platform - http://www.jython.org/index.html
You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.
If that works for you, it's certainly the simplest solution you can get. Otherwise you can use org.python.util.PythonInterpreter from the new Java6 interpreter support.
A simple example from the top of my head - but should work I hope: (no error checking done for brevity)
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\nsys.path.append('pathToModules if they are not there by default')\nimport yourModule");
// execute a function that takes a string and returns a string
PyObject someFunc = interpreter.get("funcName");
PyObject result = someFunc.__call__(new PyString("Test!"));
String realResult = (String) result.__tojava__(String.class);
As of 2021, Jython does not support Python 3.x
I think there are some important things to consider first with how strong you wish to have the linking between Java and Python.
Firstly Do you only want to call functions or do you actually want Python code to change the data in your java objects? This is very important. If you only want to call some Python code with or without arguments, then that is not very difficult. If your arguments are primitives it makes it even more easy. However, if you want to have Java class implement member functions in Python, which change the data of the Java object, then this is not so easy or straight forward.
Secondly are we talking CPython, or will Jython do? I would say CPython is where its at! I would advocate this is why Python is so kool! Having such high abstractions however access to C or C++ when needed. Imagine if you could have that in Java. This question is not even worth asking if Jython is ok because then it is easy anyway.
So I have played with the following methods, and listed them from easy to difficult:
Java to Jython
Advantages: Trivially easy. Have actual references to Java objects
Disadvantages: No CPython, Extremely Slow!
Jython from Java is so easy, and if this is really enough then great. However it is very slow and no CPython! Is life worth living without CPython? I don't think so! You can easily have Python code implementing your member functions for you Java objects.
Java to Jython to CPython via Pyro
Pyro is the remote object module for Python. You have some object on a CPython interpreter, and you can send it objects which are transferred via serialization and it can also return objects via this method. Note that if you send a serialized Python object from Jython and then call some functions which change the data in its members, then you will not see those changes in Java. You just need to remember to send back the data which you want from Pyro. This, I believe, is the easiest way to get to CPython! You do not need any JNI or JNA or SWIG or .... You don't need to know any C, or C++. Kool huh?
Advantages:
- Access to CPython
- Not as difficult as following methods
Disadvantages:
- Cannot change the member data of Java objects directly from Python
- Is somewhat indirect (Jython is middle man)
Java to C/C++ via JNI/JNA/SWIG to Python via Embedded interpreter (maybe using BOOST Libraries?)
OMG this method is not for the faint of heart. And I can tell you it has taken me very long to achieve this in with a decent method. Main reason you would want to do this is so that you can run CPython code which as full rein over you java object. There are major things to consider before deciding to try and breed Java (which is like a chimp) with Python (which is like a horse). Firstly if you crash the interpreter, that's lights out for you program! And don't get me started on concurrency issues! In addition, there is a lot of boiler, I believe I have found the best configuration to minimize this boiler but it is still a lot! So how to go about this:
Consider that C++ is your middle man, your objects are actually C++ objects! Good that you know that now. Just write your object as if your program is in C++ and not Java, with the data you want to access from both worlds. Then you can use the wrapper generator called SWIG to make this accessible to java and compile a dll which you call (System.load(dllNameHere)) in Java. Get this working first, then move on to the hard part!
To get to Python you need to embed an interpreter. Firstly I suggest doing some hello interpreter programs or this tutorial Embedding Python in C/C. Once you have that working, its time to make the horse and the monkey dance! You can send you C++ object to Python via [boost][3] . I know I have not given you the fish, merely told you where to find the fish. Some pointers to note for this when compiling.
When you compile boost you will need to compile a shared library. And you need to include and link to the stuff you need from jdk, ie jawt.lib, jvm.lib, (you will also need the client jvm.dll in your path when launching the application) As well as the python27.lib or whatever and the boost_python-vc100-mt-1_55.lib. Then include Python/include, jdk/include, boost and only use shared libraries (dlls) otherwise boost has a teary. And yeah full on I know. There are so many ways in which this can go sour. So make sure you get each thing done block by block. Then put them together.
Yes, this way is fine, but you can not run python script in constructor method, if so, it will be dead recursive at your code. please see the following code. you run PythonScriptTest class, it will run python script first, then python script will invoke PythonScriptTest.SpawnPlayer() method.
java code:
package com.xxx.jython;
import org.python.core.PyFunction;
import org.python.util.PythonInterpreter;
public class PythonScriptTest {
public static void main(String[] args) {
PythonScriptTest f = new PythonScriptTest();
f.executePythonScript();
}
public PythonScriptTest(){
}
public void executePythonScript() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("/home/XXX/XXX/util.py");
PyFunction pyFuntion = (PyFunction) interpreter.get("InGameCommand", PyFunction.class);
pyFuntion.__call__();
}
public void SpawnPlayer() {
System.out.println("Run SpawnPlayer method ##################");
}
}
Python scripts, named util.py:
import sys.path as path
# the following path is eclipse output class dir
# does not contain java class package path.
path.append("/home/XXX/XXX/Test/bin")
from com.xxx.jython import PythonScriptTest
def add(a, b):
return a + b
def InGameCommand():
myJava = PythonScriptTest()
myJava.SpawnPlayer()
need to jython.jar
execute python code in java.
import org.python.util.PythonInterpreter; public class PythonScript{ public static void main(String args[]){ PythonInterpreter interpreter = new PythonInterpreter(); interpreter.exec("days=('One','Two','Three','Four'); "); interpreter.exec("print days[1];"); } }invoke python script method in java.
python script file, named test.py
def add(a, b): return a + bjava code:
import org.python.core.PyFunction; import org.python.core.PyInteger; import org.python.core.PyObject; import org.python.util.PythonInterpreter; public class PythonScript { public static void main(String args[]) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("/home/XXX/XXX/test.py"); PyFunction pyFuntion = (PyFunction)interpreter.get("add",PyFunction.class); int a = 10, b = 20 ; PyObject pyobj = pyFuntion.__call__(new PyInteger(a), new PyInteger(b)); System.out.println("result = " + pyobj.toString()); } }run python script in java
python script file, named test.py:
number=[1,10,4,30,7,8,40] print number number.sort() print numberjava code:
import org.python.util.PythonInterpreter; public class FirstJavaScript { public static void main(String args[]) { PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile("/home/XXX/XXX/test.py"); } }
You can use PyObject.__call__(Object... args) to invoke any callable Python object. You can get the PyFunction representing your function from the java side the same way you example is getting the python employee class.
Alternativeley, you can hide this behind a single method interface on the java side by calling __tojava__(Interface.class) on the function you retrieved from the Python interpreter.
Detailed example (actually tested!):
python file:
def tmp():
return "some text"
java:
public interface I{
public String tmp();
}
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from test import tmp");
PyObject tmpFunction = interpreter.get("tmp");
System.err.println(tmpFunction.getClass());
I i = (I) x.__tojava__(I.class);
System.err.println(i.tmp());
}
output:
class org.python.core.PyFunction
some text
Importing only a method isn't possible because in Java, methods (or functions) aren't first-class objects, i.e. there's no way to refer to a method without first referring to some class (or interface). Even static methods are enclosed in a class and you refer to them via the class object.
However, you can get fairly close with the solution in introduced in Jython 2.5.2: Jython functions work directly as implementations of single abstract method Java interfaces (see http://www.zyasoft.com/pythoneering/2010/09/jython-2.5.2-beta-2-is-released/). So you can define an interface in Java - it's essential that it contains exactly one method definition:
interface MyInterface {
int multiply(int x, int y);
}
Plus something like this in Jython:
myFunction = lambda x, y : x * y
and use that as a MyInterface in Java. You still have to use some sort of factory pattern, as described in the article you linked to, to get the Jython function to Java, but something like this works (probably contains errors, but the idea is):
PyObject myFunction = interpreter.get("myFunction");
MyInterface myInterface = (MyInterface)myFunction.__tojava__(MyInterface.class);
int x = myInterface.multiply(2, 3); // Should return 6.