I am trying to create a hybrid application with python back-end and java GUI and for that purpose I am using jython to access the data from the GUI.
I wrote code using a standard Python 3.7.4 virtual environment and it worked "perfectly". But when I try to run the same code on jython it doesn't work so it seems that in jython some packages like threading are overwritten with java functionality.
My question is how can I use the threading package for example from python but in jython environment?
Here is the error:
Exception in thread Thread-1:Traceback (most recent call last):
File "/home/dexxrey/jython2.7.0/Lib/threading.py", line 222, in _Thread__bootstrap
self.run()
self._target(*self._args, **self._kwargs)
Since you have already decoupled the application i.e using python for backend and java for GUI, why not stick to that and build in a communication layer between the backend and frontend, this layer could either be REST or any Messaging framework.
I think one issue you might be facing is that you are running on Jython 2.7.0 (~Python 2.7 compatible) but your code is written for CPython 3.7.4. So you might be facing Python 2 vs 3 issues.
The threading module in Jython is indeed different from CPython i.e. it is making use of JVM threading. However the intension is to be API compatible with Python 2.7 code so if it doesn't run that should be considered a bug.
My first suggestion would be try Jython 2.7.1 it contains many fixes over 2.7.0 https://www.jython.org/download however I suspect it still might not work. Check if your code runs on CPython 2.7 https://www.python.org/downloads/release/python-2716/ if it does then that sounds like a Jython bug. Open a ticket with details to reproduce at https://bugs.jython.org/
Can Python invoke the Java Framework?
I want to know whether a Python project can invoke a Java Framework, I find a Java Framework in GitHub, whether I can use it in my Python project?
Jython
Jython is one method of calling Java from python -- actually, you run your Python inside Java JVM. This gives you access to almost any Java that runs on JVM, but comes with many limitations.
Because Jython is running python inside the JVM, this gives you acess to almost any Java library. However, you are very restricted in what Python you can use: you can only use Python 2.7, and can import pure Python libraries only (compiled Python libraries with C will not run on Jython).
For an example of a project that uses Jython: Processing.py runs on Jython in order to access the Processing Java API and its ecosystem of Java libraries.
https://github.com/jdf/processing.py
Note that Jython 2 and its docs are quite old, and that the developers are uncertain if / when Jython 3 will be released.
https://github.com/jython/jython3
py4j
py4j is a different approach -- it is "A Bridge between Python and Java" and lets native python code access separate Java running in a separate JVM. Note however that the python and Java code must be running in parallel and communicating through a gateway interface. This is communication between separately running processes -- you are not spinning up a JVM from Python or inside Python.
For example: on the JVM side pass myObject to a new GatewayServer(myObject); on the Python side create a JavaGateway() Python object and use it to communicate with the Java myObject.
Normally Python and Java have their own interpreters/VM's and cannot be shared. It is possible to use Jython but has limitations (fe. python version and support/compatibility with other python packages).
The interpreter and JVM do not match: Java has strict typing, python not. Java compiles and run, python is an interpreter and can change code in runtime (if you want). These are extra challenges why putting all in a same environment is very complex.
There are possibilities like a client/server architecture, but the feasability depends on the level of the framework.
Most of the time low level frameworks are optimized to run directly inside your application process. Any loose coupling will introduce performance and security and compatibility issues. Just think about how reflection will work or multiple inheritance.
If it is a high level framework (fe able to run stand alone) it is more feasable to use some sort of client/server. But still you have to develop a lot for it.
Industry standard is just to implement the framework of your desire in the language you want, then you can get also all the benefits of your platform.
I am creating a Windows program that so far has a .bat file calling a .pyw file, and I need functions from Java and C++. How can I do this?(I don't mind creating a new batch or python file, and I already have the header file for the C++ section and a .jar file for my java components. (For Java I use Eclipse Java Mars, and it's Java 8u101)) Thanks!!!
This is rather simple for C++: you have to compile a library with the function, import it in Python and... call it! Python has a powerful ctypes module in the standard library to handle this kind of tasks.
Here is an example of loading print() function from hypothetical libc.dll.
from ctypes import *
libc = cdll.LoadLibrary("libc.dll")
>>> print(libc.time(None))
1150640792
Calling Java from Python is covered here: How to call a java function from python/numpy?
You can load C++ function and execute it from Python like BasicWolf explained in his answer. For Java, Jython might be a good approach. But then there's a problem - you will need to be dependent on Jython which is not up to date with the latest versions of Python. You will face compatibility issues with different libraries too.
I would recommend compiling your C++ and Java functions to create individual binaries out of them. Then execute these binaries from within Python, passing the arguments as command line parameters. This way you can keep using CPython. You can interoperate with programs written in any language.
I have seen in answered here that if you want to call a python script from java, you can use jython as a option.
But have seen other answers as well saying, you can use Process or ProcessBuilder and call their exec or start methods to run the python script.
As I understand jython allows you to program python in you java code, but it allows you to call python scripts as well via, PythonInterpreter.execfile.
So I'm wondering what are my options if I want to call a python script (e.g. text processing script which uses nltk) from my java code and along with some arguments and return the results back to my java programme? which option should I use?
Jython is an implementation of the Python language for the Java platform
(source)
You can simply use ProcessBuilder if there is a regular python script on a machine that has regular python installed. This saves you from having to include a whole python runtime in your java application. You can pass parameters quite easily, the returned text is a little trickier: See http://examples.javacodegeeks.com/core-java/lang/processbuilder/java-lang-processbuilder-example/ or other examples. Basically anything that the python program prints can be captured that way.
However if you don't like external dependencies and prefer shipping everything in a single application you can try jython. It has some limitations though since it doesn't come with all those modules and it seems it may have difficulties with C modules. Getting Python's nltk.wordnet module working for Jython looks like an explanation on how to get nltk to run with it. Arguments and return values should be simpler with jython since the integration is better. And if you want more than just printed text, Jython can even call into java code directly from python. That would give you interesting options for hybrid code.
What is the best way to call java from python?
(jython and RPC are not an option for me).
I've heard of JCC: http://pypi.python.org/pypi/JCC/1.9
a C++ code generator for calling Java from C++/Python
But this requires compiling every possible call; I would prefer another solution.
I've hear about JPype: http://jpype.sourceforge.net/
tutorial: http://www.slideshare.net/onyame/mixing-python-and-java
import jpype
jpype.startJVM(path to jvm.dll, "-ea")
javaPackage = jpype.JPackage("JavaPackageName")
javaClass = javaPackage.JavaClassName
javaObject = javaClass()
javaObject.JavaMethodName()
jpype.shutdownJVM()
This looks like what I need.
However, the last release is from Jan 2009 and I see people failing to compile JPype.
Is JPype a dead project?
Are there any other alternatives?
You could also use Py4J. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway() # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass() # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method
As opposed to Jython, one part of Py4J runs in the Python VM so it is always "up to date" with the latest version of Python and you can use libraries that do not run well on Jython (e.g., lxml). The other part runs in the Java VM you want to call.
The communication is done through sockets instead of JNI and Py4J has its own protocol (to optimize certain cases, to manage memory, etc.)
Disclaimer: I am the author of Py4J
Here is my summary of this problem: 5 Ways of Calling Java from Python
http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)
Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype
I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.
Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.
Pyjnius docs and Github.
From the github page:
A Python module to access Java classes as Python classes using JNI.
PyJNIus is a "Work In Progress".
Quick overview
>>> from jnius import autoclass
>>> autoclass('java.lang.System').out.println('Hello world')
Hello world
>>> Stack = autoclass('java.util.Stack')
>>> stack = Stack()
>>> stack.push('hello')
>>> stack.push('world')
>>> print stack.pop()
world
>>> print stack.pop()
hello
If you're in Python 3, there's a fork of JPype called JPype1-py3
pip install JPype1-py3
This works for me on OSX / Python 3.4.3. (You may need to export JAVA_HOME=/Library/Java/JavaVirtualMachines/your-java-version)
from jpype import *
startJVM(getDefaultJVMPath(), "-ea")
java.lang.System.out.println("hello world")
shutdownJVM()
I'm on OSX 10.10.2, and succeeded in using JPype.
Ran into installation problems with Jnius (others have too), Javabridge installed but gave mysterious errors when I tried to use it, PyJ4 has this inconvenience of having to start a Gateway server in Java first, JCC wouldn't install. Finally, JPype ended up working. There's a maintained fork of JPype on Github. It has the major advantages that (a) it installs properly and (b) it can very efficiently convert java arrays to numpy array (np_arr = java_arr[:])
The installation process was:
git clone https://github.com/originell/jpype.git
cd jpype
python setup.py install
And you should be able to import jpype
The following demo worked:
import jpype as jp
jp.startJVM(jp.getDefaultJVMPath(), "-ea")
jp.java.lang.System.out.println("hello world")
jp.shutdownJVM()
When I tried calling my own java code, I had to first compile (javac ./blah/HelloWorldJPype.java), and I had to change the JVM path from the default (otherwise you'll get inexplicable "class not found" errors). For me, this meant changing the startJVM command to:
jp.startJVM('/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/MacOS/libjli.dylib', "-ea")
c = jp.JClass('blah.HelloWorldJPype')
# Where my java class file is in ./blah/HelloWorldJPype.class
...
I've been integrating a lot of stuff into Python lately, including Java. The most robust method I've found is to use IKVM and a C# wrapper.
IKVM has a neat little application that allows you to take any Java JAR, and convert it directly to .Net DLL. It simply translates the JVM bytecode to CLR bytecode. See http://sourceforge.net/p/ikvm/wiki/Ikvmc/ for details.
The converted library behaves just like a native C# library, and you can use it without needing the JVM. You can then create a C# DLL wrapper project, and add a reference to the converted DLL.
You can now create some wrapper stubs that call the methods that you want to expose, and mark those methods as DllEport. See https://stackoverflow.com/a/29854281/1977538 for details.
The wrapper DLL acts just like a native C library, with the exported methods looking just like exported C methods. You can connect to them using ctype as usual.
I've tried it with Python 2.7, but it should work with 3.0 as well. Works on Windows and the Linuxes
If you happen to use C#, then this is probably the best approach to try when integrating almost anything into python.
I'm just beginning to use JPype 0.5.4.2 (july 2011) and it looks like it's working nicely...
I'm on Xubuntu 10.04
I'm assuming that if you can get from C++ to Java then you are all set. I've seen a product of the kind you mention work well. As it happens the one we used was CodeMesh. I'm not specifically endorsing this vendor, or making any statement about their product's relative quality, but I have seen it work in quite a high volume scenario.
I would say generally that if at all possible I would recommend keeping away from direct integration via JNI if you can. Some simple REST service approach, or queue-based architecture will tend to be simpler to develop and diagnose. You can get quite decent perfomance if you use such decoupled technologies carefully.
Through my own experience trying to run some java code from within python in a manner similar to how python code runs within java code in python, I was unable to find a straightforward methodology.
My solution to my problem was by running this java code as BeanShell scripts by calling the BeanShell interpreter as a shell command from within my python code after editing the java code in a temporary file with the appropriate packages and variables.
If what I am talking about is helpful in any manner, I am glad to help you share more details of my solutions.