kivy / pyjnius Goto Github PK
View Code? Open in Web Editor NEWAccess Java classes from Python
Home Page: https://pyjnius.readthedocs.org
License: MIT License
Access Java classes from Python
Home Page: https://pyjnius.readthedocs.org
License: MIT License
I'm using Olap4j, and, as documented on page 11 of this PDF, Java is supposed to automatically unwrap JDBC connection objects to gain access to their true connection, which works under Jython but not PyJNIus. (This seems like magic to me, so I don't understand the details.)
test.py
file given at the bottom of this report in the Mondrian directory. Run it. Under Jython 2.7, it runs fine, but under PyJNIus, it reports:Traceback (most recent call last):
File "test.py", line 23, in <module>
result = connection.prepareOlapStatement(mdx).executeQuery()
AttributeError: 'java.sql.Connection' object has no attribute 'prepareOlapStatement'
test.py:
import sys
_is_jython = sys.platform.startswith("java")
if _is_jython:
from java.sql import DriverManager
from org.olap4j import OlapConnection
else:
from jnius import autoclass
DriverManager = autoclass('java.sql.DriverManager')
OlapConnection = autoclass('org.olap4j.OlapConnection')
url = 'jdbc:mondrian:JdbcDrivers=org.postgresql.Driver;Jdbc=jdbc:postgresql://localhost/foodmart?user=postgres&password=password;Catalog=demo/FoodMart.xml;'
mdx = '''
SELECT
[Measures].[Customer Count] ON COLUMNS,
[Gender].[Gender].Members ON ROWS
FROM [Sales]
'''
connection = DriverManager.getConnection(url)
result = connection.prepareOlapStatement(mdx).executeQuery()
enums reflections works out-of-the-box according to my tests, but there is still a problem with reflection, see followup.
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
C:\Python27x64\lib\distutils\dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running install
running build
running build_py
running build_ext
skipping 'jnius\jnius.c' Cython extension (up-to-date)
building 'jnius' extension
C:\MinGW32\bin\gcc.exe -mno-cygwin -mdll -O -Wall -DMS_WIN64 -I/usr/include -I/usr/include\linux -IC:\Python27x64\include -IC:\Python27x64\PC -c jnius\jnius.c -o build\temp.win-amd64-2.7\Release\jnius\jnius.o
cc1.exe: error: unrecognized command line option '-mno-cygwin'
error: command 'gcc' failed with exit status 1
I want to run HelloWorld.java, could you tell me how ro run?
There is an internal function to do this, but it not accessible in Python
I'm trying to install python for android, but it gets caught up at this point and I've tried everything to get around it... Fails on jnius compilation. Anyone have a similar issue?
Leaving ARM enviromnent
Call build_pyjnius
Entering in ARM enviromnent
Compiler found at /opt/android-ndk/toolchains/arm-linux-androideabi-4.4.3/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc
/home/eric/workspace/python-for-android/build/python-install/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
building 'jnius' extension
arm-linux-androideabi-gcc -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -fPIC -I/home/eric/workspace/python-for-android/build/python-install/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'arm-linux-androideabi-gcc' failed with exit status 1
find: `cython': No such file or directory
/home/eric/workspace/python-for-android/build/python-install/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
building 'jnius' extension
arm-linux-androideabi-gcc -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -mandroid -fomit-frame-pointer --sysroot /opt/android-ndk//platforms/android-14/arch-arm -fPIC -I/home/eric/workspace/python-for-android/build/python-install/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c:1:2: error: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'arm-linux-androideabi-gcc' failed with exit status 1
my code raises
raise JavaException('Invalid python object for this '
'argument. Want {0!r}, got {1!r}'.format(
argtype[1:-1], py_arg))
https://github.com/kivy/pyjnius/blob/master/jnius/jnius_conversion.pxi#L58
Can I "cast/wrap" my python object which can be one of the following str, unicode, list, int, float, long (and dict in the future) to/in a Java Object so that I don't have to explicitly do a switch like the following:
if isinstance(my_object, str):
my_object = java.lang.String(my_object)
# etc...
Local reference returned from NewObjectA is not deleted.
(I would make pull request, but it looks like it's not possible to have two at once)
git pull: https://github.com/zielmicha/pyjnius/
or patch:
diff --git a/jnius/jnius_export_class.pxi b/jnius/jnius_export_class.pxi
index 790d967..a62a913 100644
--- a/jnius/jnius_export_class.pxi
+++ b/jnius/jnius_export_class.pxi
@@ -225,6 +225,7 @@ cdef class JavaClass(object):
self.__javaclass__))
self.j_self = create_local_ref(j_env, j_self)
+ j_env[0].DeleteLocalRef(j_env, j_self)
finally:
if j_args != NULL:
free(j_args)
I'm trying to access Android's clipboard using jnius, but I'm running into some issues. So far I've tried the following:
if platform() == 'android':
from jnius import autoclass
Context = autoclass('org.renpy.android.PythonActivity')
ClipboardManager = autoclass('android.content.ClipboardManager')
ClipData = autoclass('android.content.ClipData')
ClipDescription = autoclass('android.content.ClipDescription')
ClipItem = autoclass('android.content.ClipData.Item') #it throws an error saying that the class was not found
context = Context.mActivity
vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) #vibrator implementation works very well, thans tshirtman!
android_clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE)
I then tried putting data to the clipboard using an example provided here (http://developer.android.com/guide/topics/text/copy-paste.html):
clip = ClipData.newPlainText("simple text","Hello, World!") #it throws an error saying that it was expecting java/lang/charsequence' but got 'simple text'
android_clipboard.setPrimaryClip(clip)
Is it actually possible to access the aforementioned classes through pyjnius. If yes, what am I doing wrong in the implementation. Thanks for any help.
modified the setup.py to include the following properties
library_dirs = ['/System/Library/Frameworks/JavaVM.framework/Libraries']
include_dirs = ['/System/Library/Frameworks/JavaVM.framework/Headers']
[15:39:24][/usr/local/pyjnius]> python2.7 setup.py install
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running install
running build
running build_py
running build_ext
skipping 'jnius/jnius.c' Cython extension (up-to-date)
running install_lib
running install_egg_info
Removing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
Writing /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
[15:39:51][/usr/local/pyjnius]> ls -al /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
-rw-r--r-- 1 felixgao admin 829 Oct 9 15:39 /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/jnius-1.1_dev-py2.7.egg-info
[15:43:07][/usr/local/pyjnius]> python2.7
Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
from jnius import *
Traceback (most recent call last):
File "", line 1, in
File "jnius/init.py", line 12, in
from .jnius import *
ImportError: No module named jnius
>>> from jnius import autoclass
>>> syso = autoclass('java.lang.System').out
>>> syso.println("hi")
hi
>>> syso.printf("hi\n")
/usr/lib/python2.7/site-packages/jnius/jnius.so in jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14462)()
JavaException: No methods matching your arguments
>>> syso.printf("hi %s\n", "jnius")
/usr/lib/python2.7/site-packages/jnius/jnius.so in jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14462)()
JavaException: No methods matching your arguments
Take a look at this snippet:
class DelayedRunnable(PythonJavaClass):
__javainterfaces__ = ['java/lang/Runnable']
def __init__(self, callback, *args, **kwargs):
super(DelayedRunnable, self).__init__(*args, **kwargs)
self.callback = callback
@java_method('()V')
def run(self):
self.callback()
handler = Handler(Looper.getMainLooper())
handler.postDelayed(DelayedRunnable(init_receiver), 1000)
The DelayedRunnable() instance will be deleted by Python GC, before java use it.
This is why we can have than kind of weirdness:
I/python (25412): !! create_proxy_instance() on 1548769344 <__main__.DelayedRunnable object at 0x5c505840>
...
I/python (25412): !! invoke0() from (1548769344, 1548769344) ('', 'system', 'dock', 'multi')
I/python (25412): Exception AttributeError: "'tuple' object has no attribute 'invoke'" in 'jnius.jnius.invoke0' ignored
We need to keep a reference of the DelayedRunnable until the java proxy is really deleted. Keeping a reference is not an issue, detecting when to release it is the issue.
Maybe http://docs.oracle.com/javase/6/docs/api/java/lang/ref/PhantomReference.html could help us, but i'm not sure about how to use it.
--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362784-link-python-gc-to-java-gc-for-pythonjavaclass?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).This section doesn't return a good jre_home on my box. What's an example of the properly formed directory? I have several Java installations going.
jre_home = environ.get('JRE_HOME')
if not jre_home:
jre_home = subprocess.Popen('readlink -f /usr/bin/java | sed "s:bin/java::"',
shell=True, stdout=subprocess.PIPE).communicate()[0].strip()
I have no idea where to begin installing this. I want to use it with kivy on android for the tts module. I can't find any documentation except for how to use it after it's installed. I tried using 'make' but my system doesn't recognize the 'make' command even after installing make. Need more detail on this. Maybe step by step (including installing make).
I ran across a confusing JavaException
when trying to call a Java method stored in a class variable:
from jnius import autoclass
System = autoclass('java.lang.System')
# This works:
System.out.println('Hello World')
map(System.out.println, ['Hello World'])
println = System.out.println
map(println, ['Hello World'])
class MyClass(object):
def __init__(self):
self.println = System.out.println # Instance variables are fine
map(MyClass().println, ['Hello World'])
# This causes an exception:
class MyClass(object):
println = System.out.println # But class variables cause errors
map(MyClass.println, ['Hello World'])
Running this code produces the following output:
Hello World
Hello World
Hello World
Hello World
Traceback (most recent call last):
File "jniustest.py", line 19, in <module>
map(MyClass.println, ['Hello World'])
File "jnius_export_class.pxi", line 745, in jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:15502)
jnius.JavaException: No methods matching your arguments
This is an odd edge-case with an easy workaround (don't store Java methods in class variables), but I thought I'd report it here in case anyone else encounters it.
--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362787-javaexception-when-calling-java-methods-stored-in-python-class-variables?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).Neo4J is ready to use jnius as the binding library of its python library if its possible to ship it in binary format.
I guess it's possible, it should be shipped at least for Windows 32bit/64bit against Java 6 (if it matters) and Unix-like 32bits/64bits, MacOS X should be supported too.
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
Running this code under Jython works. Running the equivalent Java works. I'm doing it just as the docs say to. But PyJNIus prints:
Traceback (most recent call last):
File "test.py", line 25, in <module>
olapConnection = connection.unwrap(OlapConnection)
File "jnius_export_class.pxi", line 487, in jnius.JavaMethod.__call__ (jnius/jnius.c:11969)
File "jnius_conversion.pxi", line 58, in jnius.populate_args (jnius/jnius.c:4110)
jnius.JavaException: Invalid python object for this argument. Want 'java/lang/Class', got <class 'jnius.reflect.org.olap4j.OlapConnection'>
for the following code:
import sys
_is_jython = sys.platform.startswith("java")
if _is_jython:
from java.sql import DriverManager
from org.olap4j import OlapConnection
else:
from jnius import autoclass
DriverManager = autoclass('java.sql.DriverManager')
OlapConnection = autoclass('org.olap4j.OlapConnection')
url = "jdbc:mondrian:JdbcDrivers=org.postgresql.Driver;Jdbc=jdbc:postgresql://localhost/foodmart?user=postgres&password=password;Catalog=demo/FoodMart.xml;"
mdx = '''
SELECT
[Measures].[Customer Count] ON COLUMNS,
[Gender].[Gender].Members ON ROWS
FROM [Sales]
'''
connection = DriverManager.getConnection(url)
olapConnection = connection.unwrap(OlapConnection)
result = olapConnection.prepareOlapStatement(mdx).executeQuery()
(To run the test code, use same setup procedure as bug #21.)
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
$ pip install jnius
gcc: error: jnius/jnius.c: No such file or directory
It is both redundant, and inconvenient. They're all under the jnius package after all
Getting this issue:
Hi,
I'm trying to run pyjnius on Debian wheezy. The vast majority of the tests (make tests) fails. It seems to be (mostly) related to the fact that it doesn't find the jars required for the tests. The failure looks like this:
======================================================================
ERROR: test_instance_methods (test_basics.BasicsTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/michael/hacking/testkraut/db/pyjnius/tests/test_basics.py", line 31, inn test_instance_methods
test = autoclass('org.jnius.BasicsTest')()
File "/home/michael/hacking/testkraut/db/pyjnius/jnius/reflect.py", line 109, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:7418)
JavaException: Class not found 'org/jnius/BasicsTest'
I can work with the standard library without problems:
>>> from jnius import autoclass
>>> autoclass('java.lang.System').out.println('Hello world')
Hello world
but accessing any other JAR fails.
I tried Debian's openjdk 6 and 7 -- the result is the same. It there any (versioned) dependency that I am missing?
Is there any way to set JVM heap size? something that works like this:
java -Xmx512m
And there are some questions about CLASSPATH. When I set it in code, can't find my classes:
environ['CLASSPATH'] = 'absolute/path/file.jar'
Even setting that out of my python file, doesn't change anything:
export CLASSPATH="absolute/path/file.jar"
Hi,
There are some problems with ouput arguments. If I write, for example :
String = autoclass('java.lang.String')
string = String("word".encode('utf-8'))
btarray= [0]*4
string.getBytes(0,4,btarray,0)
print btarray
It output :
[0, 0, 0, 0]
So the output argument(btarray) is not written
Same with :
[.....]
usbConnection = cast('android.hardware.usb.UsbDeviceConnection', UsbManager.openDevice(dev))
response= [0]*4
usbConnection.bulkTransfer(epIN, response, 4, 1000); # Try to read from USB (Host Mode API)
print response
If I use a bytearray (btarray=bytearray()), I get this error :
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/sdcard/testAn.py", line 13, in <module>
string.getBytes(0,4,btarray,0)
File "jnius_export_class.pxi", line 813, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:17292)
JavaException: No methods matching your arguments
And if I use a list (btarray=list()), I get this :
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/sdcard/testAn.py", line 13, in <module>
string.getBytes(0,4,btarray,0)
File "jnius_export_class.pxi", line 819, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:17414)
File "jnius_export_class.pxi", line 577, in jnius.jnius.JavaMethod.__call__ (jnius/jnius.c:15021)
File "jnius_export_class.pxi", line 658, in jnius.jnius.JavaMethod.call_method (jnius/jnius.c:15691)
File "jnius_utils.pxi", line 39, in jnius.jnius.check_exception (jnius/jnius.c:2200)
JavaException: JVM exception occured
Thanks a lot.
I use jnius with Apache + mod_wsgi with django. I made a jar file in JRE lib to invoke it with jnius.
It seems work, but with 50% Success rate.
The Apache error as follows:
child pid XXXXX exit signal Segmentation fault (11)
Anyone help?
Thanks a lot.
I have my $CLASSPATH
set to a string with wildcards, which is legal and documented (although it may be vendor-specific). This is normally expanded before assigning to java.class.path
, but PyJNIus sets it directly.
Expand wildcards before assigning to java.class.path
.
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
I compile jnius on MS Win 8 ( 64ibt ). The Python ver. is 2.7 ( 32bit ). The Oracle Java JDK ver. is 1.7.0_25 ( 32bit ) The C/C++ compiler was TDM-GCC 4.7 ( 32bit )
After some hack, I finish the compile process and install the egg
If I kept the jnius.pyd as original name, the Python intepreter complain no dll loaded
If I rename the jnius.pyd to jnius.dll, the Python interpreter complained No module named jnius.
was trying to compile it with mingw and vc 2008, but even after adding the correct includes from the jdk (subdir "win32"), I get this error:
C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo /Ox /MD /W3 /GS- /DNDEBUG "-Ic:\Program Files (x86)\Java\jdk1.7.0_05\include" "-Ic:\Program Files (x86)\Java\jdk1.7.0_05\include\win32" -IC:\Python27\include -IC:\Python27\PC /Tcjnius\jnius.c /Fobuild\temp.win32-2.7\Release\jnius\jnius.obj
jnius.c
jnius\jnius.c(961) : error C2373: 'JNI_CreateJavaVM': Neudefinition; unterschiedliche Modifizierer
c:\Program Files (x86)\Java\jdk1.7.0_05\include\jni.h(1938): Siehe Deklaration von 'JNI_CreateJavaVM'
Can't reach to build it from source, so I tried phyjnius which brings an py2.7 installer !
And when I call "import jnius"
I've got :
File "c:\python27\lib\site-packages\jnius__init__.py", line 12, in
from .jnius import *
ImportError: DLL load failed: Le module spécifié est introuvable.
(but works on winXP sp3 32bit)
python I jnius.jnius.JavaException: Invalid class argument, want 'java/util/Collection', got 'java/util/Set'
but java sets ARE java collections.
testcase:
>>> DB = autoclass("java.awt.image.DataBufferDouble")
>>> DB([[.5]], 1)
JavaException: No constructor matching your arguments
>>> db = DB(1)
>>> db.getBankData()
JavaException: Invalid return definition for array
both errors shouldn’t happen, both are due to the fact that both convert_pyarray_to_java
and convert_jarray_to_python
can receive a definition starting with "["
, i.e. a multidimensional array. e.g. the above function getBankData
has the return type signature [[D
, so convert_jarray_to_python(j_env, "[D", j_object)
is called and fails.
an idea for convert_jarray_to_python
would be to insert another elif r=="["
and calling convert_jarray_to_python
recursively inside.
I'm trying to get Toast working with jnius, but I can't get past java.lang.CharSequence. From a Kivy Remote Console session:
>>> from jnius import autoclass
>>> PythonActivity = autoclass('org.renpy.android.PythonActivity')
>>> Toast = autoclass('android.widget.Toast')
>>> toast = Toast(PythonActivity.mActivity)
>>> toast.setText("Hello, world")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "jnius_export_class.pxi", line 745, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14793)
JavaException: No methods matching your arguments
>>> JavaString = autoclass('java.lang.String')
>>> msg = JavaString("Hello, world")
>>> toast.setText(msg)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "jnius_export_class.pxi", line 751, in jnius.jnius.JavaMultipleMethod.__call__ (jnius/jnius.c:14919)
File "jnius_export_class.pxi", line 503, in jnius.jnius.JavaMethod.__call__ (jnius/jnius.c:12462)
File "jnius_conversion.pxi", line 51, in jnius.jnius.populate_args (jnius/jnius.c:3987)
File "jnius_utils.pxi", line 63, in jnius.jnius.check_assignable_from (jnius/jnius.c:2037)
JavaException: Unable to found the class for 'java/lang/CharSequence'
I have a kivy app that needs to close threads pythonically when exited, but when the user touches the back or home buttons on the navigation bar the app freezes because the python activity did not get a proper exit() call and thus the threads keep running. Since Android does not allow for the Nav bar to be disabled I need a work around for this. I'm thinking that using PyJnius I can have a 'os._exit(True)' called when the backbutton is pressed. The only thing is I have no idea how I would do this. I came here to ask the question because I don't know of a forum where I could ask. Thank you for any help!
Loading some classes on android simply break because of the limit of jni reference table, would be great to find a way around this.
Exemple found just now, that crashes kivy-remote-shell on its own.
>>> from jnius import autoclass
>>> WebView = autoclass('android.webkit.WebView')
Connection to 192.168.0.10 closed by remote host.
The following results in a core dump:
import threading
from jnius import autoclass
class MyThread(threading.Thread):
def run(self):
autoclass('java.lang.System').out.println('Hello world')
for i in range(2):
MyThread().start()
Hi, All
I have to invoke a static java method in my task(django-celery) through pyjnius. It works fine for the first task. But it throws exception while executing the 2nd task. Check the jvm log, it shows
Internal exceptions (1 events):
Event: 0.058 Thread 0x0000000001ae2800 Threw 0x0000000704a06140 at /build/buildd/openjdk-7-7u25-2.3.10/build/openjdk/hotspot/src/share/vm/prims/jni.cpp:3994
Seems this is thread problem, right?
How can i fix this?
BTW, misja, can i make it works through gevent?
--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362782-pyjnius-is-still-not-thread-safe?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).Now that we have varargs and a classpath, we should create a new tag for packagers.
When I install the pyjnius by pip, I get the JDK 7 and install it. then when I run pip install pyjnius
, it's report the error as /Library/Java/JavaVirtualMachines/jdk1.7.0_06.jdk/Contents/Home/include/jni.h:45:10: fatal error: 'jni_md.h' file not found
(after I has set the JDK_HOME
and JRE_HOME
)
And I find the file at '/Library/Java/JavaVirtualMachines/jdk1.7.0_06.jdk/Contents/Home/include/darwin/` and copy it to parent directory.
Then, I retry installing, and get the result like clang: error: no such file or directory: '/Library/Java/JavaVirtualMachines/jdk1.7.0_06.jdk/Contents/Home/jre/lib/amd64/server'
.
I can't find the ire/lib/amd64/server
. what can I do?
The accelerometer example in README.md seems wrong (out of date?). Specifically, it seems Hardware.accelerometerEnable()
should be Hardware.accelerometerEnable(True)
- the former fails on android with a message about incorrect number of arguments.
Part of the problem is that JavaMetaClass.new assumes that it will always be called to create a proxy, when it will be called for every descendant class. On the same line, handling of the jclass_registry must be restricted to actual proxies. Something else I found is that the treatment of objects returned from Java is lax, which makes it impossible to pass them back to Java methods.
I can work on some of this issues in due time.
I very much like how fast jnius is at loading Java, and being able to use the latest versions of Python.
--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362796-inheriting-from-java-classes-doesn-t-work?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).Actually manages to leak 3 references each call!
git pull https://github.com/zielmicha/pyjnius
Or patch:
diff --git a/jnius/jnius_utils.pxi b/jnius/jnius_utils.pxi
index 7d893b4..05d54f7 100644
--- a/jnius/jnius_utils.pxi
+++ b/jnius/jnius_utils.pxi
@@ -77,6 +77,9 @@ cdef bytes lookup_java_object_name(JNIEnv *j_env, jobject j_obj):
cdef jmethodID jmeth = j_env[0].GetMethodID(j_env, jcls2, 'getName', '()Ljava/lang/String;')
cdef jobject js = j_env[0].CallObjectMethod(j_env, jcls, jmeth)
name = convert_jobject_to_python(j_env, b'Ljava/lang/String;', js)
+ j_env[0].DeleteLocalRef(j_env, js)
+ j_env[0].DeleteLocalRef(j_env, jcls)
+ j_env[0].DeleteLocalRef(j_env, jcls2)
return name.replace('.', '/')
Make seems to be looking in the wrong place for some of the java libs (or a place I don't have them).
(2d)stu@beezlebub:~/projects/external/pyjnius$ ls /usr/lib/jvm/jdk1.7.0_04/
bin COPYRIGHT db include jre lib LICENSE man README.html release src.zip THIRDPARTYLICENSEREADME.txt
(2d)stu@beezlebub:~/projects/external/pyjnius$ ls /usr/lib/jvm/jdk1.7.0_04/lib/
ct.sym dt.jar ir.idl jconsole.jar jexec orb.idl sa-jdi.jar tools.jar visualvm
(2d)stu@beezlebub:~/projects/external/pyjnius$
Here's the output of make
(2d)stu@beezlebub:~/projects/external/pyjnius$ make
python setup.py build_ext --inplace -f
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
building 'jnius' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/lib/jvm/jdk1.7.0_04/include -I/usr/lib/jvm/jdk1.7.0_04/include/linux -I/usr/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c: In function ‘__pyx_pf_5jnius_13MetaJavaClass_2resolve_class’:
jnius/jnius.c:7025:13: warning: variable ‘__pyx_v_meta’ set but not used [-Wunused-but-set-variable]
jnius/jnius.c: In function ‘__pyx_pf_5jnius_9JavaField___cinit__’:
jnius/jnius.c:9458:13: warning: variable ‘__pyx_v_definition’ set but not used [-Wunused-but-set-variable]
jnius/jnius.c: In function ‘__pyx_pf_5jnius_10JavaMethod___cinit__’:
jnius/jnius.c:11061:13: warning: variable ‘__pyx_v_definition’ set but not used [-Wunused-but-set-variable]
jnius/jnius.c: In function ‘__pyx_pf_5jnius_18JavaMultipleMethod___cinit__’:
jnius/jnius.c:13182:13: warning: variable ‘__pyx_v_definition’ set but not used [-Wunused-but-set-variable]
gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro build/temp.linux-x86_64-2.7/jnius/jnius.o -L/usr/lib/jvm/jdk1.7.0_04/lib/amd64/server -ljvm -o /home/stu/projects/external/pyjnius/jnius/jnius.so -Wl,-rpath /usr/lib/jvm/jdk1.7.0_04/lib/amd64/server
gcc: error: /usr/lib/jvm/jdk1.7.0_04/lib/amd64/server: No such file or directory
error: command 'gcc' failed with exit status 1
make: *** [build_ext] Error 1
(2d)stu@beezlebub:~/projects/external/pyjnius$
I get a JVM error while trying to create a Toast. Example code from Kivy Remote:
from jnius import autoclass
AndroidString = autoclass('java.lang.String')
PythonActivity = autoclass('org.renpy.android.PythonActivity')
Toast = autoclass('android.widget.Toast')
msg = AndroidString("Hello, world!".encode('utf-8'))
toast = Toast.makeText(PythonActivity.mActivity, msg, Toast.LENGTH_SHORT)
CHECK FOR org/renpy/android/PythonActivity android/content/Context True
CHECK FOR java/lang/String java/lang/CharSequence True
Traceback (most recent call last):
File "", line 1, in
File "jnius_export_class.pxi", line 751, in jnius.jnius.JavaMultipleMethod.call (jnius/jnius.c:14919)
File "jnius_export_class.pxi", line 508, in jnius.jnius.JavaMethod.call (jnius/jnius.c:12495)
File "jnius_export_class.pxi", line 665, in jnius.jnius.JavaMethod.call_staticmethod (jnius/jnius.c:13745)
File "jnius_utils.pxi", line 40, in jnius.jnius.check_exception (jnius/jnius.c:1855)
JavaException: JVM exception occured
Installing collected packages: jnius
Running setup.py install for jnius
cythoning jnius/jnius.pyx to jnius/jnius.c
Error compiling Cython file:
------------------------------------------------------------
...
'JavaObject', 'JavaClass', 'JavaMethod', 'JavaField', 'MetaJavaClass',
'JavaException', 'cast', 'find_javaclass')
from libc.stdlib cimport malloc, free
include "jni.pxi"
^
------------------------------------------------------------
Hi Pyjnius,
Thank you for this great project. It save me a lot of time.
I use it with django. It works fine at develop mode, the normal linux account + django builtin web server.
I mean use command line as 'python manage.py runserver'
However, It failed to invoke my java class in same folder, at apache mode + mod_wsgi. The exception message is 'Class XXX not found'. But the 'java.lang.System' class can be found easily.
I checked the python os.environ between dev mode and apache mode.
Can you help me?
Thanks a lot.
This makes itterating over them painful.
example:
@java_method('(ILjava/lang/Object;)Ljava/lang/Object;')
if you don't know jni, this is impossible to understand/write correctly.
something like
from jnius import Object, Int
@java_method((Int, Object), Object)
maybe?
--- Want to back this issue? **[Post a bounty on it!](https://www.bountysource.com/issues/1362781-jni-style-signatures-are-ugly-change-the-api-of-interfaces-to-use-a-more-java-like-interface?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github)** We accept bounties via [Bountysource](https://www.bountysource.com/?utm_campaign=plugin&utm_content=tracker%2F77133&utm_medium=issues&utm_source=github).I have a question, what is the best way to create an array of bytes ?
with a python list ?
In [1]: from jnius import autoclass
In [2]: byte_class = autoclass('java.lang.Byte')
In [3]: [byte_class(50), byte_class(60)]
Out[3]:
[<java.lang.Byte at 0x2296d70 jclass=java/lang/Byte jself=<jnius.LocalRef object at 0x19016e8>>,
<java.lang.Byte at 0x2296e30 jclass=java/lang/Byte jself=<jnius.LocalRef object at 0x1901698>>]
Thx !
As builds were working at the beginning I was wondering why it now fails to build.
As you can see here: https://launchpad.net/~kivy-team/+archive/kivy-daily/+build/4275170
(build log included)
After checking the setup.py for a while I found the reason at
https://github.com/kivy/pyjnius/blob/master/setup.py#L68
Which just cares about i386 and amd64. What about using platform.machine()?
In case of armel and armhf we would need to add a dict to point at the folder "arm", but this isn't really a problem.
Also x86_64 would be needed to be translated to amd64.
Programming in python based on lists and other collections. I think it's better to convert them instantly. I mean you should reduce switching between python and JVM. Take a look at this example:
while iterator.hasNext():
print iterator.next()
That needs switching to JVM for each item. But there isn't any need if you convert Java Iterable to python list. Or this one with same performance issue:
for i in range(arr.length):
print list[i]
I have the following errors with the latest version:
python setup.py build_ext --inplace -f
/usr/lib/python2.7/distutils/dist.py:267: UserWarning: Unknown distribution option: 'install_requires'
warnings.warn(msg)
running build_ext
cythoning jnius/jnius.pyx to jnius/jnius.c
...
#XXX not working with cython?
#jint (RegisterNatives)(JNIEnv, jclass, const_JNINativeMethod_, jint)
jint (UnregisterNatives)(JNIEnv, jclass)
jint (MonitorEnter)(JNIEnv, jobject)
jint (MonitorExit)(JNIEnv, jobject)
jint (GetJavaVM)(JNIEnv, JavaVM_*)
/home/desnos/python/pyjnius/jnius/jni.pxi:375:42: 'JavaVM' is not a type identifier
...
jboolean JNI_FALSE
ctypedef struct JavaVMInitArgs:
jint version
jint nOptions
jboolean ignoreUnrecognized
JavaVMOption *options
/home/desnos/python/pyjnius/jnius/jnius_jvm_desktop.pxi:12:8: 'JavaVMOption' is not a type identifier
...
j_env[0].ExceptionClear(j_env)
raise JavaException('JVM exception occured')
cdef dict assignable_from = {}
cdef void check_assignable_from(JNIEnv *env, JavaClass jc, bytes signature) except *:
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:44:45: 'JavaClass' is not a type identifier
...
cdef dict assignable_from = {}
cdef void check_assignable_from(JNIEnv *env, JavaClass jc, bytes signature) except *:
cdef jclass cls
# if we have a JavaObject, it's always ok.
if signature == 'java/lang/Object':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:48:17: Comparisons between bytes/unicode and str are not portable to Python 3
...
cls = env[0].FindClass(env, signature)
if cls == NULL:
raise JavaException('Unable to found the class for {0!r}'.format(
signature))
result = bool(env[0].IsAssignableFrom(env, jc.j_cls, cls))
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:66:53: Cannot convert Python object to 'jclass'
...
for index in range(len(sign_args)):
r = sign_args[index]
arg = args[index]
if r == 'Z':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:103:13: Comparisons between bytes/unicode and str are not portable to Python 3
...
if not isinstance(arg, bool):
return -1
score += 10
continue
if r == 'B':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:109:13: Comparisons between bytes/unicode and str are not portable to Python 3
...
if not isinstance(arg, int):
return -1
score += 10
continue
if r == 'C':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:115:13: Comparisons between bytes/unicode and str are not portable to Python 3
...
if not isinstance(arg, str) or len(arg) != 1:
return -1
score += 10
continue
if r == 'S' or r == 'I' or r == 'J':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:121:13: Comparisons between bytes/unicode and str are not portable to Python 3
...
if not isinstance(arg, str) or len(arg) != 1:
return -1
score += 10
continue
if r == 'S' or r == 'I' or r == 'J':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:121:25: Comparisons between bytes/unicode and str are not portable to Python 3
...
if not isinstance(arg, str) or len(arg) != 1:
return -1
score += 10
continue
if r == 'S' or r == 'I' or r == 'J':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:121:37: Comparisons between bytes/unicode and str are not portable to Python 3
...
score += 5
continue
else:
return -1
if r == 'F' or r == 'D':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:131:13: Comparisons between bytes/unicode and str are not portable to Python 3
...
score += 5
continue
else:
return -1
if r == 'F' or r == 'D':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:131:25: Comparisons between bytes/unicode and str are not portable to Python 3
...
if arg is None:
score += 10
continue
# if it's a string, accept any python string
if r == 'java/lang/String' and isinstance(arg, basestring):
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:150:17: Comparisons between bytes/unicode and str are not portable to Python 3
...
score += 10
continue
# if it's a generic object, accept python string, or any java
# class/object
if r == 'java/lang/Object':
^
/home/desnos/python/pyjnius/jnius/jnius_utils.pxi:156:17: Comparisons between bytes/unicode and str are not portable to Python 3
...
cdef bytes r = definition[1:-1]
cdef JavaObject ret_jobject
cdef JavaClass ret_jc
# we got a generic object -> lookup for the real name instead.
if r == 'java/lang/Object':
^
/home/desnos/python/pyjnius/jnius/jnius_conversion.pxi:82:9: Comparisons between bytes/unicode and str are not portable to Python 3
...
# we got a generic object -> lookup for the real name instead.
if r == 'java/lang/Object':
r = lookup_java_object_name(j_env, j_object)
# if we got a string, just convert back to Python str.
if r == 'java/lang/String':
^
/home/desnos/python/pyjnius/jnius/jnius_conversion.pxi:86:9: Comparisons between bytes/unicode and str are not portable to Python 3
building 'jnius' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/lib/jvm/java-6-sun-1.6.0.26/include -I/usr/lib/jvm/java-6-sun-1.6.0.26/include/linux -I/usr/include/python2.7 -c jnius/jnius.c -o build/temp.linux-x86_64-2.7/jnius/jnius.o
jnius/jnius.c:1:2: erreur: #error Do not use this file, it is the result of a failed Cython compilation.
error: command 'gcc' failed with exit status 1
make: *** [build_ext] Erreur 1
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.