Name | scyjava JSON |
Version |
1.10.0
JSON |
| download |
home_page | None |
Summary | Supercharged Java access from Python |
upload_time | 2024-06-11 16:50:06 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.8 |
license | The Unlicense |
keywords |
java
maven
cross-language
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
[![build status](https://github.com/scijava/scyjava/actions/workflows/build.yml/badge.svg)](https://github.com/scijava/scyjava/actions/workflows/build.yml)
[![codecov](https://codecov.io/gh/scijava/scyjava/branch/main/graph/badge.svg?token=NLK3ADZUCU)](https://codecov.io/gh/scijava/scyjava)
Supercharged Java access from Python.
Built on [JPype](https://jpype.readthedocs.io/en/latest/)
and [jgo](https://github.com/scijava/jgo).
## Use Java classes from Python
```python
>>> from scyjava import jimport
>>> System = jimport('java.lang.System')
>>> System.getProperty('java.version')
'1.8.0_252'
```
To pass parameters to the JVM, such as an increased max heap size:
```python
>>> from scyjava import config, jimport
>>> config.add_option('-Xmx6g')
>>> Runtime = jimport('java.lang.Runtime')
>>> Runtime.getRuntime().maxMemory() / 2**30
5.33349609375
```
See the [JPype documentation](https://jpype.readthedocs.io/en/latest/)
for all the gritty details on how this wrapping works.
## Use Maven artifacts from remote repositories
### From Maven Central
```python
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0)
>>> from scyjava import config, jimport
>>> config.endpoints.append('org.python:jython-slim:2.7.2')
>>> jython = jimport('org.python.util.jython')
>>> jython.main([])
Jython 2.7.2 (v2.7.2:925a3cc3b49d, Mar 21 2020, 10:12:24)
[OpenJDK 64-Bit Server VM (JetBrains s.r.o)] on java1.8.0_152-release
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=1, releaselevel='final', serial=0)
>>> from java.lang import System
>>> System.getProperty('java.version')
u'1.8.0_152-release'
```
### From other Maven repositories
```python
>>> from scyjava import config, jimport
>>> config.enable_headless_mode()
>>> config.add_repositories({'scijava.public': 'https://maven.scijava.org/content/groups/public'})
>>> config.endpoints.append('net.imagej:imagej:2.1.0')
>>> ImageJ = jimport('net.imagej.ImageJ')
>>> ij = ImageJ()
>>> formula = "10 * (Math.cos(0.3*p[0]) + Math.sin(0.3*p[1]))"
>>> ArrayImgs = jimport('net.imglib2.img.array.ArrayImgs')
>>> blank = ArrayImgs.floats(64, 16)
>>> sinusoid = ij.op().image().equation(blank, formula)
>>> print(ij.op().image().ascii(sinusoid))
,,,--+oo******oo+--,,,,,--+oo******o++--,,,,,--+oo******o++--,,,
...,--+ooo**oo++--,....,,--+ooo**oo++-,,....,,--+ooo**oo++-,,...
...,--++oooo++--,... ...,--++oooo++--,... ...,--++oooo++-,,...
..,--++++++--,.. ..,--++o+++--,.. .,,--++o+++--,..
..,,-++++++-,,. ..,,-++++++-,,. ..,--++++++-,,.
.,,--++++--,,. .,,--++++--,,. .,,--++++--,..
.,,--++++--,,. .,,-+++++--,,. .,,-+++++--,,.
..,--++++++--,.. ..,--++++++--,.. ..,--++++++-,,..
..,,-++oooo++-,,.. ..,,-++oooo++-,,.. ..,,-++ooo+++-,,..
...,,-++oooooo++-,,.....,,-++oooooo++-,,.....,,-++oooooo+--,,...
.,,,-++oo****oo++-,,,.,,,-++oo****oo+--,,,.,,,-++oo****oo+--,,,.
,,--++o***OO**oo++-,,,,--++o***OO**oo+--,,,,--++o***OO**oo+--,,,
---++o**OOOOOO**o++-----++o**OOOOOO*oo++-----++o**OOOOOO*oo++---
--++oo*OO####OO*oo++---++oo*OO####OO*oo++---++o**OO####OO*oo++--
+++oo*OO######O**oo+++++oo*OO######O**oo+++++oo*OO######O**oo+++
+++oo*OO######OO*oo+++++oo*OO######OO*oo+++++oo*OO######OO*oo+++
```
See the [jgo documentation](https://github.com/scijava/jgo) for more about Maven endpoints.
## Convert between Python and Java data structures
### Convert Java collections to Python
```python
>>> from scyjava import jimport
>>> HashSet = jimport('java.util.HashSet')
>>> moves = {'jump', 'duck', 'dodge'}
>>> fish = {'walleye', 'pike', 'trout'}
>>> jbirds = HashSet()
>>> for bird in ('duck', 'goose', 'swan'): jbirds.add(bird)
...
True
True
True
>>> jbirds.isdisjoint(moves)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'java.util.HashSet' object has no attribute 'isdisjoint'
>>> from scyjava import to_python as j2p
>>> j2p(jbirds).isdisjoint(moves)
False
>>> j2p(jbirds).isdisjoint(fish)
True
```
### Convert Python collections to Java
```python
>>> squares = [n**2 for n in range(1, 10)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> squares.stream()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'stream'
>>> from scyjava import to_java as p2j
>>> p2j(squares).stream()
<java object 'java.util.stream.ReferencePipeline.Head'>
```
```python
>>> from scyjava import jimport
>>> HashSet = jimport('java.util.HashSet')
>>> jset = HashSet()
>>> pset = {1, 2, 3}
>>> jset.addAll(pset)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: No matching overloads found for java.util.Set.addAll(set), options are:
public abstract boolean java.util.Set.addAll(java.util.Collection)
>>> from scyjava import to_java as p2j
>>> jset.addAll(p2j(pset))
True
>>> jset.toString()
'[1, 2, 3]'
```
## Available functions
```
>>> import scyjava
>>> help(scyjava)
...
FUNCTIONS
add_java_converter(converter: scyjava._convert.Converter) -> None
Add a converter to the list used by to_java.
:param converter: A Converter going from python to java
add_py_converter(converter: scyjava._convert.Converter) -> None
Add a converter to the list used by to_python.
:param converter: A Converter from java to python
available_processors() -> int
Get the number of processors available to the JVM.
This function is a shortcut for Java's
Runtime.getRuntime().availableProcessors().
:return: The number of available processors.
:raise RuntimeError: if the JVM has not yet been started.
enable_python_scripting(context)
Adds a Python script runner object to the ObjectService of the given
SciJava context. Intended for use in conjunction with
'org.scijava:scripting-python'.
:param context: The org.scijava.Context containing the ObjectService
where the PythonScriptRunner should be injected.
gc() -> None
Do a round of Java garbage collection.
This function is a shortcut for Java's System.gc().
:raise RuntimeError: If the JVM has not started yet.
get_version(java_class_or_python_package) -> str
Return the version of a Java class or Python package.
For Python package, uses importlib.metadata.version if available
(Python 3.8+), with pkg_resources.get_distribution as a fallback.
For Java classes, requires org.scijava:scijava-common on the classpath.
The version string is extracted from the given class's associated JAR
artifact (if any), either the embedded Maven POM if the project was built
with Maven, or the JAR manifest's Specification-Version value if it exists.
See org.scijava.VersionUtils.getVersion(Class) for further details.
is_arraylike(arr: Any) -> bool
Return True iff the object is arraylike: possessing
.shape, .dtype, .__array__, and .ndim attributes.
:param arr: The object to check for arraylike properties
:return: True iff the object is arraylike
is_awt_initialized() -> bool
Return true iff the AWT subsystem has been initialized.
Java starts up its AWT subsystem automatically and implicitly, as
soon as an action is performed requiring it -- for example, if you
jimport a java.awt or javax.swing class. This can lead to deadlocks
on macOS if you are not running in headless mode and did not invoke
those actions via the jpype.setupGuiEnvironment wrapper function;
see the Troubleshooting section of the scyjava README for details.
is_jarray(data: Any) -> bool
Return whether the given data object is a Java array.
is_jvm_headless() -> bool
Return true iff Java is running in headless mode.
:raise RuntimeError: If the JVM has not started yet.
is_memoryarraylike(arr: Any) -> bool
Return True iff the object is memoryarraylike:
an arraylike object whose .data type is memoryview.
:param arr: The object to check for memoryarraylike properties
:return: True iff the object is memoryarraylike
is_version_at_least(actual_version: str, minimum_version: str) -> bool
Return a boolean on a version comparison.
Requires org.scijava:scijava-common on the classpath.
Returns True if the given actual version is greater than or
equal to the specified minimum version, or False otherwise.
See org.scijava.VersionUtils.compare(String, String) for further details.
is_xarraylike(xarr: Any) -> bool
Return True iff the object is xarraylike:
possessing .values, .dims, and .coords attributes,
and whose .values are arraylike.
:param arr: The object to check for xarraylike properties
:return: True iff the object is xarraylike
isjava(data) -> bool
Return whether the given data object is a Java object.
jarray(kind, lengths: Sequence)
Create a new n-dimensional Java array.
:param kind: The type of array to create. This can either be a particular
type of object as obtained from jimport, or else a special code for one of
the eight primitive array types:
* 'b' for byte
* 'c' for char
* 'd' for double
* 'f' for float
* 'i' for int
* 'j' for long
* 's' for short
* 'z' for boolean
:param lengths: List of lengths for the array. For example:
`jarray('z', [3, 7])` is the equivalent of `new boolean[3][7]` in Java.
You can pass a single integer to make a 1-dimensional array of that length.
:return: The newly allocated array
jclass(data)
Obtain a Java class object.
Supported types include:
A. Name of a class to look up -- e.g. "java.lang.String" --
which returns the equivalent of Class.forName("java.lang.String").
B. A static-style class reference -- e.g. String --
which returns the equivalent of String.class.
C. A Java object -- e.g. foo --
which returns the equivalent of foo.getClass().
Note that if you pass a java.lang.Class object, you will get back Class.class,
i.e. the Java class for the Class class. :-)
:param data: The object from which to glean the class.
:return: A java.lang.Class object, suitable for use with reflection.
:raise TypeError: if the argument is not one of the aforementioned types.
jimport(class_name: str)
Import a class from Java to Python.
:param class_name: Name of the class to import.
:return:
A pointer to the class, which can be used to
e.g. instantiate objects of that class.
jinstance(obj, jtype) -> bool
Test if the given object is an instance of a particular Java type.
:param obj: The object to check.
:param jtype: The Java type, as either a jimported class or as a string.
:return: True iff the object is an instance of that Java type.
jstacktrace(exc) -> str
Extract the Java-side stack trace from a Java exception.
Example of usage:
from scyjava import jimport, jstacktrace
try:
Integer = jimport('java.lang.Integer')
nan = Integer.parseInt('not a number')
except Exception as exc:
print(jstacktrace(exc))
:param exc: The Java Throwable from which to extract the stack trace.
:return: A multi-line string containing the stack trace, or empty string
if no stack trace could be extracted.
jvm_started() -> bool
Return true iff a Java virtual machine (JVM) has been started.
jvm_version() -> str
Gets the version of the JVM as a tuple, with each dot-separated digit
as one element. Characters in the version string beyond only numbers
and dots are ignored, in line with the java.version system property.
Examples:
* OpenJDK 17.0.1 -> [17, 0, 1]
* OpenJDK 11.0.9.1-internal -> [11, 0, 9, 1]
* OpenJDK 1.8.0_312 -> [1, 8, 0]
If the JVM is already started, this function returns the equivalent of:
jimport('java.lang.System')
.getProperty('java.version')
.split('.')
In case the JVM is not started yet, a best effort is made to deduce
the version from the environment without actually starting up the
JVM in-process. If the version cannot be deduced, a RuntimeError
with the cause is raised.
memory_max() -> int
Get the maximum amount of memory that the JVM will attempt to use.
This number will always be greater than or equal to memory_total().
In case the JVM was configured with -Xmx flag upon startup (e.g. using
the scyjava.config.set_heap_max function), the value will typically
correspond approximately, but not exactly, to the configured value.
This function is a shortcut for Java's Runtime.getRuntime().maxMemory().
:return: The maximum memory in bytes.
:raise RuntimeError: if the JVM has not yet been started.
memory_total() -> int
Get the total amount of memory currently reserved by the JVM.
This number will always be less than or equal to memory_max().
In case the JVM was configured with -Xms flag upon startup (e.g. using
the scyjava.config.set_heap_min function), the initial value will typically
correspond approximately, but not exactly, to the configured value,
although it is likely to grow over time as more Java objects are allocated.
This function is a shortcut for Java's Runtime.getRuntime().totalMemory().
:return: The total memory in bytes.
:raise RuntimeError: if the JVM has not yet been started.
memory_used() -> int
Get the amount of memory currently in use by the JVM.
This function is a shortcut for
Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory().
:return: The used memory in bytes.
:raise RuntimeError: if the JVM has not yet been started.
numeric_bounds(the_type: type) -> Union[Tuple[int, int], Tuple[float, float], Tuple[NoneType, NoneType]]
Get the minimum and maximum values for the given numeric type.
For example, a Java long returns (int(Long.MIN_VALUE), int(Long.MAX_VALUE)),
whereas a Java double returns (float(-Double.MAX_VALUE), float(Double.MAX_VALUE)).
:param the_type: The type whose minimum and maximum values are needed.
:return:
The minimum and maximum values as a two-element tuple of int or float,
or a two-element tuple of None if no known bounds.
shutdown_jvm() -> None
Shut down the JVM.
This function makes a best effort to clean up Java resources first.
In particular, shutdown hooks registered with scyjava.when_jvm_stops
are sequentially invoked.
Then, if the AWT subsystem has started, all AWT windows (as identified
by the java.awt.Window.getWindows() method) are disposed to reduce the
risk of GUI resources delaying JVM shutdown.
Finally, the jpype.shutdownJVM() function is called. Note that you can
set the jpype.config.destroy_jvm flag to request JPype to destroy the
JVM explicitly, although setting this flag can lead to delayed shutdown
times while the JVM is waiting for threads to finish.
Note that if the JVM is not already running, then this function does
nothing! In particular, shutdown hooks are skipped in this situation.
:raise RuntimeError: if this method is called while in Jep mode.
start_jvm(options=None) -> None
Explicitly connect to the Java virtual machine (JVM). Only one JVM can
be active; does nothing if the JVM has already been started. Calling
this function directly is typically not necessary, because the first
time a scyjava function needing a JVM is invoked, one is started on the
fly with the configuration specified via the scijava.config mechanism.
:param options:
List of options to pass to the JVM.
For example: ['-Dfoo=bar', '-XX:+UnlockExperimentalVMOptions']
to_java(obj: Any, **hints: Dict) -> Any
Recursively convert a Python object to a Java object.
Supported types include:
* str -> String
* bool -> Boolean
* int -> Integer, Long or BigInteger as appropriate
* float -> Float, Double or BigDecimal as appropriate
* dict -> LinkedHashMap
* set -> LinkedHashSet
* list -> ArrayList
There is typically one single destination conversion type and value that
makes sense. For example, Python str always converts to java.lang.String.
But in some cases, there are multiple options that can be controlled by
passing key/value pairs as hints. The base scyjava library includes:
* int + type='byte' -> Byte
* int + type='short' -> Short
* int + type='int' -> Integer
* int + type='long' -> Long
* int + type='bigint' -> BigInteger
* float + type='float' -> Float
* float + type='double' -> Double
* float + type='bigdec' -> BigDecimal
But the scyjava conversion framework is extensible and other
packages may introduce converters supporting additional hints.
In the absence of a hint, scyjava makes a best effort to use a sensible
destination type and value:
* int values in [-2**31, 2**31-1] convert to Integer
* int values in [-2**63, 2**63-1] but outside int range convert to Long
* int values outside Java long range convert to BigInteger
* conversion of int to Byte or Short must be requested via a hint
* float values in Float range convert to Float
* float inf, -inf, and nan convert to Float
* float values in Double range but outside float range convert to Double
* float values outside double range convert to BigDecimal
:param obj:
The Python object to convert.
:param hints:
An optional dictionary of hints, to help scyjava
make decisions about how to do the conversion.
:return: A corresponding Java object with the same contents.
:raise TypeError: if the argument is not one of the aforementioned types.
to_python(data: Any, gentle: bool = False) -> Any
Recursively convert a Java object to a Python object.
Supported types include:
* String, Character -> str
* Boolean -> bool
* Byte, Short, Integer, Long, BigInteger -> int
* Float, Double, BigDecimal -> float
* Map -> collections.abc.MutableMapping (dict-like)
* Set -> collections.abc.MutableSet (set-like)
* List -> collections.abc.MutableSequence (list-like)
* Collection -> collections.abc.Collection
* Iterable -> collections.abc.Iterable
* Iterator -> collections.abc.Iterator
:param data:
The Java object to convert.
:param gentle:
If set, and the type cannot be converted, leaves
the data alone rather than raising a TypeError.
:return: A corresponding Python object with the same contents.
:raise TypeError:
if the argument is not one of the aforementioned types,
and the gentle flag is not set.
when_jvm_starts(f) -> None
Registers a function to be called when the JVM starts (or immediately).
This is useful to defer construction of Java-dependent data structures
until the JVM is known to be available. If the JVM has already been
started, the function executes immediately.
:param f: Function to invoke when scyjava.start_jvm() is called.
when_jvm_stops(f) -> None
Registers a function to be called just before the JVM shuts down.
This is useful to perform cleanup of Java-dependent data structures.
Note that if the JVM is not already running when shutdown_jvm is
called, then these registered callback functions will be skipped!
:param f: Function to invoke when scyjava.shutdown_jvm() is called.
```
## Troubleshooting
On macOS, attempting to use AWT/Swing from Python will cause a hang,
unless you do one of two things:
1. Start Java in headless mode:
```python
from scyjava import config, jimport
config.enable_headless_mode()
```
In which case, you'll get `java.awt.HeadlessException` instead of a
hang when you attempt to do something graphical, e.g. create a window.
2. Or install [PyObjC](https://pyobjc.readthedocs.io/), specifically the
`pyobjc-core` and `pyobjc-framework-cocoa` packages from conda-forge,
or `pyobjc` from PyPI; and then do your AWT-related things inside of
a `jpype.setupGuiEnvironment` call on the main Python thread:
```python
import jpype, scyjava
scyjava.start_jvm()
def hello():
JOptionPane = scyjava.jimport('javax.swing.JOptionPane')
JOptionPane.showMessageDialog(None, "Hello world")
jpype.setupGuiEnvironment(hello)
```
In which case, the `setupGuiEnvironment` call will block the main Python
thread forever.
Raw data
{
"_id": null,
"home_page": null,
"name": "scyjava",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.8",
"maintainer_email": null,
"keywords": "java, maven, cross-language",
"author": null,
"author_email": "SciJava developers <ctrueden@wisc.edu>",
"download_url": "https://files.pythonhosted.org/packages/55/6a/2a65fcf6eb48537543a2e0a8465035495702daed999057c48909854a44ce/scyjava-1.10.0.tar.gz",
"platform": null,
"description": "[![build status](https://github.com/scijava/scyjava/actions/workflows/build.yml/badge.svg)](https://github.com/scijava/scyjava/actions/workflows/build.yml)\n[![codecov](https://codecov.io/gh/scijava/scyjava/branch/main/graph/badge.svg?token=NLK3ADZUCU)](https://codecov.io/gh/scijava/scyjava)\n\nSupercharged Java access from Python.\n\nBuilt on [JPype](https://jpype.readthedocs.io/en/latest/)\nand [jgo](https://github.com/scijava/jgo).\n\n## Use Java classes from Python\n\n```python\n>>> from scyjava import jimport\n>>> System = jimport('java.lang.System')\n>>> System.getProperty('java.version')\n'1.8.0_252'\n```\n\nTo pass parameters to the JVM, such as an increased max heap size:\n\n```python\n>>> from scyjava import config, jimport\n>>> config.add_option('-Xmx6g')\n>>> Runtime = jimport('java.lang.Runtime')\n>>> Runtime.getRuntime().maxMemory() / 2**30\n5.33349609375\n```\n\nSee the [JPype documentation](https://jpype.readthedocs.io/en/latest/)\nfor all the gritty details on how this wrapping works.\n\n## Use Maven artifacts from remote repositories\n\n### From Maven Central\n\n```python\n>>> import sys\n>>> sys.version_info\nsys.version_info(major=3, minor=8, micro=5, releaselevel='final', serial=0)\n>>> from scyjava import config, jimport\n>>> config.endpoints.append('org.python:jython-slim:2.7.2')\n>>> jython = jimport('org.python.util.jython')\n>>> jython.main([])\nJython 2.7.2 (v2.7.2:925a3cc3b49d, Mar 21 2020, 10:12:24)\n[OpenJDK 64-Bit Server VM (JetBrains s.r.o)] on java1.8.0_152-release\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sys\n>>> sys.version_info\nsys.version_info(major=2, minor=7, micro=1, releaselevel='final', serial=0)\n>>> from java.lang import System\n>>> System.getProperty('java.version')\nu'1.8.0_152-release'\n```\n\n### From other Maven repositories\n\n```python\n>>> from scyjava import config, jimport\n>>> config.enable_headless_mode()\n>>> config.add_repositories({'scijava.public': 'https://maven.scijava.org/content/groups/public'})\n>>> config.endpoints.append('net.imagej:imagej:2.1.0')\n>>> ImageJ = jimport('net.imagej.ImageJ')\n>>> ij = ImageJ()\n>>> formula = \"10 * (Math.cos(0.3*p[0]) + Math.sin(0.3*p[1]))\"\n>>> ArrayImgs = jimport('net.imglib2.img.array.ArrayImgs')\n>>> blank = ArrayImgs.floats(64, 16)\n>>> sinusoid = ij.op().image().equation(blank, formula)\n>>> print(ij.op().image().ascii(sinusoid))\n,,,--+oo******oo+--,,,,,--+oo******o++--,,,,,--+oo******o++--,,,\n...,--+ooo**oo++--,....,,--+ooo**oo++-,,....,,--+ooo**oo++-,,...\n ...,--++oooo++--,... ...,--++oooo++--,... ...,--++oooo++-,,...\n ..,--++++++--,.. ..,--++o+++--,.. .,,--++o+++--,..\n ..,,-++++++-,,. ..,,-++++++-,,. ..,--++++++-,,.\n .,,--++++--,,. .,,--++++--,,. .,,--++++--,..\n .,,--++++--,,. .,,-+++++--,,. .,,-+++++--,,.\n ..,--++++++--,.. ..,--++++++--,.. ..,--++++++-,,..\n ..,,-++oooo++-,,.. ..,,-++oooo++-,,.. ..,,-++ooo+++-,,..\n...,,-++oooooo++-,,.....,,-++oooooo++-,,.....,,-++oooooo+--,,...\n.,,,-++oo****oo++-,,,.,,,-++oo****oo+--,,,.,,,-++oo****oo+--,,,.\n,,--++o***OO**oo++-,,,,--++o***OO**oo+--,,,,--++o***OO**oo+--,,,\n---++o**OOOOOO**o++-----++o**OOOOOO*oo++-----++o**OOOOOO*oo++---\n--++oo*OO####OO*oo++---++oo*OO####OO*oo++---++o**OO####OO*oo++--\n+++oo*OO######O**oo+++++oo*OO######O**oo+++++oo*OO######O**oo+++\n+++oo*OO######OO*oo+++++oo*OO######OO*oo+++++oo*OO######OO*oo+++\n```\n\nSee the [jgo documentation](https://github.com/scijava/jgo) for more about Maven endpoints.\n\n## Convert between Python and Java data structures\n\n### Convert Java collections to Python\n\n```python\n>>> from scyjava import jimport\n>>> HashSet = jimport('java.util.HashSet')\n>>> moves = {'jump', 'duck', 'dodge'}\n>>> fish = {'walleye', 'pike', 'trout'}\n>>> jbirds = HashSet()\n>>> for bird in ('duck', 'goose', 'swan'): jbirds.add(bird)\n...\nTrue\nTrue\nTrue\n>>> jbirds.isdisjoint(moves)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'java.util.HashSet' object has no attribute 'isdisjoint'\n>>> from scyjava import to_python as j2p\n>>> j2p(jbirds).isdisjoint(moves)\nFalse\n>>> j2p(jbirds).isdisjoint(fish)\nTrue\n```\n\n### Convert Python collections to Java\n\n```python\n>>> squares = [n**2 for n in range(1, 10)]\n>>> squares\n[1, 4, 9, 16, 25, 36, 49, 64, 81]\n>>> squares.stream()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nAttributeError: 'list' object has no attribute 'stream'\n>>> from scyjava import to_java as p2j\n>>> p2j(squares).stream()\n<java object 'java.util.stream.ReferencePipeline.Head'>\n```\n\n```python\n>>> from scyjava import jimport\n>>> HashSet = jimport('java.util.HashSet')\n>>> jset = HashSet()\n>>> pset = {1, 2, 3}\n>>> jset.addAll(pset)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: No matching overloads found for java.util.Set.addAll(set), options are:\n\tpublic abstract boolean java.util.Set.addAll(java.util.Collection)\n>>> from scyjava import to_java as p2j\n>>> jset.addAll(p2j(pset))\nTrue\n>>> jset.toString()\n'[1, 2, 3]'\n```\n\n## Available functions\n\n```\n>>> import scyjava\n>>> help(scyjava)\n...\nFUNCTIONS\n add_java_converter(converter: scyjava._convert.Converter) -> None\n Add a converter to the list used by to_java.\n :param converter: A Converter going from python to java\n\n add_py_converter(converter: scyjava._convert.Converter) -> None\n Add a converter to the list used by to_python.\n :param converter: A Converter from java to python\n\n available_processors() -> int\n Get the number of processors available to the JVM.\n\n This function is a shortcut for Java's\n Runtime.getRuntime().availableProcessors().\n\n :return: The number of available processors.\n :raise RuntimeError: if the JVM has not yet been started.\n\n enable_python_scripting(context)\n Adds a Python script runner object to the ObjectService of the given\n SciJava context. Intended for use in conjunction with\n 'org.scijava:scripting-python'.\n\n :param context: The org.scijava.Context containing the ObjectService\n where the PythonScriptRunner should be injected.\n\n gc() -> None\n Do a round of Java garbage collection.\n\n This function is a shortcut for Java's System.gc().\n\n :raise RuntimeError: If the JVM has not started yet.\n\n get_version(java_class_or_python_package) -> str\n Return the version of a Java class or Python package.\n\n For Python package, uses importlib.metadata.version if available\n (Python 3.8+), with pkg_resources.get_distribution as a fallback.\n\n For Java classes, requires org.scijava:scijava-common on the classpath.\n\n The version string is extracted from the given class's associated JAR\n artifact (if any), either the embedded Maven POM if the project was built\n with Maven, or the JAR manifest's Specification-Version value if it exists.\n\n See org.scijava.VersionUtils.getVersion(Class) for further details.\n\n is_arraylike(arr: Any) -> bool\n Return True iff the object is arraylike: possessing\n .shape, .dtype, .__array__, and .ndim attributes.\n\n :param arr: The object to check for arraylike properties\n :return: True iff the object is arraylike\n\n is_awt_initialized() -> bool\n Return true iff the AWT subsystem has been initialized.\n\n Java starts up its AWT subsystem automatically and implicitly, as\n soon as an action is performed requiring it -- for example, if you\n jimport a java.awt or javax.swing class. This can lead to deadlocks\n on macOS if you are not running in headless mode and did not invoke\n those actions via the jpype.setupGuiEnvironment wrapper function;\n see the Troubleshooting section of the scyjava README for details.\n\n is_jarray(data: Any) -> bool\n Return whether the given data object is a Java array.\n\n is_jvm_headless() -> bool\n Return true iff Java is running in headless mode.\n\n :raise RuntimeError: If the JVM has not started yet.\n\n is_memoryarraylike(arr: Any) -> bool\n Return True iff the object is memoryarraylike:\n an arraylike object whose .data type is memoryview.\n\n :param arr: The object to check for memoryarraylike properties\n :return: True iff the object is memoryarraylike\n\n is_version_at_least(actual_version: str, minimum_version: str) -> bool\n Return a boolean on a version comparison.\n Requires org.scijava:scijava-common on the classpath.\n\n Returns True if the given actual version is greater than or\n equal to the specified minimum version, or False otherwise.\n\n See org.scijava.VersionUtils.compare(String, String) for further details.\n\n is_xarraylike(xarr: Any) -> bool\n Return True iff the object is xarraylike:\n possessing .values, .dims, and .coords attributes,\n and whose .values are arraylike.\n\n :param arr: The object to check for xarraylike properties\n :return: True iff the object is xarraylike\n\n isjava(data) -> bool\n Return whether the given data object is a Java object.\n\n jarray(kind, lengths: Sequence)\n Create a new n-dimensional Java array.\n\n :param kind: The type of array to create. This can either be a particular\n type of object as obtained from jimport, or else a special code for one of\n the eight primitive array types:\n * 'b' for byte\n * 'c' for char\n * 'd' for double\n * 'f' for float\n * 'i' for int\n * 'j' for long\n * 's' for short\n * 'z' for boolean\n :param lengths: List of lengths for the array. For example:\n `jarray('z', [3, 7])` is the equivalent of `new boolean[3][7]` in Java.\n You can pass a single integer to make a 1-dimensional array of that length.\n :return: The newly allocated array\n\n jclass(data)\n Obtain a Java class object.\n\n Supported types include:\n\n A. Name of a class to look up -- e.g. \"java.lang.String\" --\n which returns the equivalent of Class.forName(\"java.lang.String\").\n\n B. A static-style class reference -- e.g. String --\n which returns the equivalent of String.class.\n\n C. A Java object -- e.g. foo --\n which returns the equivalent of foo.getClass().\n\n Note that if you pass a java.lang.Class object, you will get back Class.class,\n i.e. the Java class for the Class class. :-)\n\n :param data: The object from which to glean the class.\n :return: A java.lang.Class object, suitable for use with reflection.\n :raise TypeError: if the argument is not one of the aforementioned types.\n\n jimport(class_name: str)\n Import a class from Java to Python.\n\n :param class_name: Name of the class to import.\n :return:\n A pointer to the class, which can be used to\n e.g. instantiate objects of that class.\n\n jinstance(obj, jtype) -> bool\n Test if the given object is an instance of a particular Java type.\n\n :param obj: The object to check.\n :param jtype: The Java type, as either a jimported class or as a string.\n :return: True iff the object is an instance of that Java type.\n\n jstacktrace(exc) -> str\n Extract the Java-side stack trace from a Java exception.\n\n Example of usage:\n\n from scyjava import jimport, jstacktrace\n try:\n Integer = jimport('java.lang.Integer')\n nan = Integer.parseInt('not a number')\n except Exception as exc:\n print(jstacktrace(exc))\n\n :param exc: The Java Throwable from which to extract the stack trace.\n :return: A multi-line string containing the stack trace, or empty string\n if no stack trace could be extracted.\n\n jvm_started() -> bool\n Return true iff a Java virtual machine (JVM) has been started.\n\n jvm_version() -> str\n Gets the version of the JVM as a tuple, with each dot-separated digit\n as one element. Characters in the version string beyond only numbers\n and dots are ignored, in line with the java.version system property.\n\n Examples:\n * OpenJDK 17.0.1 -> [17, 0, 1]\n * OpenJDK 11.0.9.1-internal -> [11, 0, 9, 1]\n * OpenJDK 1.8.0_312 -> [1, 8, 0]\n\n If the JVM is already started, this function returns the equivalent of:\n jimport('java.lang.System')\n .getProperty('java.version')\n .split('.')\n\n In case the JVM is not started yet, a best effort is made to deduce\n the version from the environment without actually starting up the\n JVM in-process. If the version cannot be deduced, a RuntimeError\n with the cause is raised.\n\n memory_max() -> int\n Get the maximum amount of memory that the JVM will attempt to use.\n\n This number will always be greater than or equal to memory_total().\n\n In case the JVM was configured with -Xmx flag upon startup (e.g. using\n the scyjava.config.set_heap_max function), the value will typically\n correspond approximately, but not exactly, to the configured value.\n\n This function is a shortcut for Java's Runtime.getRuntime().maxMemory().\n\n :return: The maximum memory in bytes.\n :raise RuntimeError: if the JVM has not yet been started.\n\n memory_total() -> int\n Get the total amount of memory currently reserved by the JVM.\n\n This number will always be less than or equal to memory_max().\n\n In case the JVM was configured with -Xms flag upon startup (e.g. using\n the scyjava.config.set_heap_min function), the initial value will typically\n correspond approximately, but not exactly, to the configured value,\n although it is likely to grow over time as more Java objects are allocated.\n\n This function is a shortcut for Java's Runtime.getRuntime().totalMemory().\n\n :return: The total memory in bytes.\n :raise RuntimeError: if the JVM has not yet been started.\n\n memory_used() -> int\n Get the amount of memory currently in use by the JVM.\n\n This function is a shortcut for\n Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory().\n\n :return: The used memory in bytes.\n :raise RuntimeError: if the JVM has not yet been started.\n\n numeric_bounds(the_type: type) -> Union[Tuple[int, int], Tuple[float, float], Tuple[NoneType, NoneType]]\n Get the minimum and maximum values for the given numeric type.\n For example, a Java long returns (int(Long.MIN_VALUE), int(Long.MAX_VALUE)),\n whereas a Java double returns (float(-Double.MAX_VALUE), float(Double.MAX_VALUE)).\n\n :param the_type: The type whose minimum and maximum values are needed.\n :return:\n The minimum and maximum values as a two-element tuple of int or float,\n or a two-element tuple of None if no known bounds.\n\n shutdown_jvm() -> None\n Shut down the JVM.\n\n This function makes a best effort to clean up Java resources first.\n In particular, shutdown hooks registered with scyjava.when_jvm_stops\n are sequentially invoked.\n\n Then, if the AWT subsystem has started, all AWT windows (as identified\n by the java.awt.Window.getWindows() method) are disposed to reduce the\n risk of GUI resources delaying JVM shutdown.\n\n Finally, the jpype.shutdownJVM() function is called. Note that you can\n set the jpype.config.destroy_jvm flag to request JPype to destroy the\n JVM explicitly, although setting this flag can lead to delayed shutdown\n times while the JVM is waiting for threads to finish.\n\n Note that if the JVM is not already running, then this function does\n nothing! In particular, shutdown hooks are skipped in this situation.\n\n :raise RuntimeError: if this method is called while in Jep mode.\n\n start_jvm(options=None) -> None\n Explicitly connect to the Java virtual machine (JVM). Only one JVM can\n be active; does nothing if the JVM has already been started. Calling\n this function directly is typically not necessary, because the first\n time a scyjava function needing a JVM is invoked, one is started on the\n fly with the configuration specified via the scijava.config mechanism.\n\n :param options:\n List of options to pass to the JVM.\n For example: ['-Dfoo=bar', '-XX:+UnlockExperimentalVMOptions']\n\n to_java(obj: Any, **hints: Dict) -> Any\n Recursively convert a Python object to a Java object.\n\n Supported types include:\n * str -> String\n * bool -> Boolean\n * int -> Integer, Long or BigInteger as appropriate\n * float -> Float, Double or BigDecimal as appropriate\n * dict -> LinkedHashMap\n * set -> LinkedHashSet\n * list -> ArrayList\n\n There is typically one single destination conversion type and value that\n makes sense. For example, Python str always converts to java.lang.String.\n But in some cases, there are multiple options that can be controlled by\n passing key/value pairs as hints. The base scyjava library includes:\n\n * int + type='byte' -> Byte\n * int + type='short' -> Short\n * int + type='int' -> Integer\n * int + type='long' -> Long\n * int + type='bigint' -> BigInteger\n * float + type='float' -> Float\n * float + type='double' -> Double\n * float + type='bigdec' -> BigDecimal\n\n But the scyjava conversion framework is extensible and other\n packages may introduce converters supporting additional hints.\n\n In the absence of a hint, scyjava makes a best effort to use a sensible\n destination type and value:\n\n * int values in [-2**31, 2**31-1] convert to Integer\n * int values in [-2**63, 2**63-1] but outside int range convert to Long\n * int values outside Java long range convert to BigInteger\n * conversion of int to Byte or Short must be requested via a hint\n * float values in Float range convert to Float\n * float inf, -inf, and nan convert to Float\n * float values in Double range but outside float range convert to Double\n * float values outside double range convert to BigDecimal\n\n :param obj:\n The Python object to convert.\n :param hints:\n An optional dictionary of hints, to help scyjava\n make decisions about how to do the conversion.\n :return: A corresponding Java object with the same contents.\n :raise TypeError: if the argument is not one of the aforementioned types.\n\n to_python(data: Any, gentle: bool = False) -> Any\n Recursively convert a Java object to a Python object.\n\n Supported types include:\n * String, Character -> str\n * Boolean -> bool\n * Byte, Short, Integer, Long, BigInteger -> int\n * Float, Double, BigDecimal -> float\n * Map -> collections.abc.MutableMapping (dict-like)\n * Set -> collections.abc.MutableSet (set-like)\n * List -> collections.abc.MutableSequence (list-like)\n * Collection -> collections.abc.Collection\n * Iterable -> collections.abc.Iterable\n * Iterator -> collections.abc.Iterator\n\n :param data:\n The Java object to convert.\n :param gentle:\n If set, and the type cannot be converted, leaves\n the data alone rather than raising a TypeError.\n :return: A corresponding Python object with the same contents.\n :raise TypeError:\n if the argument is not one of the aforementioned types,\n and the gentle flag is not set.\n\n when_jvm_starts(f) -> None\n Registers a function to be called when the JVM starts (or immediately).\n This is useful to defer construction of Java-dependent data structures\n until the JVM is known to be available. If the JVM has already been\n started, the function executes immediately.\n\n :param f: Function to invoke when scyjava.start_jvm() is called.\n\n when_jvm_stops(f) -> None\n Registers a function to be called just before the JVM shuts down.\n This is useful to perform cleanup of Java-dependent data structures.\n\n Note that if the JVM is not already running when shutdown_jvm is\n called, then these registered callback functions will be skipped!\n\n :param f: Function to invoke when scyjava.shutdown_jvm() is called.\n```\n\n## Troubleshooting\n\nOn macOS, attempting to use AWT/Swing from Python will cause a hang,\nunless you do one of two things:\n\n1. Start Java in headless mode:\n\n ```python\n from scyjava import config, jimport\n config.enable_headless_mode()\n ```\n\n In which case, you'll get `java.awt.HeadlessException` instead of a\n hang when you attempt to do something graphical, e.g. create a window.\n\n2. Or install [PyObjC](https://pyobjc.readthedocs.io/), specifically the\n `pyobjc-core` and `pyobjc-framework-cocoa` packages from conda-forge,\n or `pyobjc` from PyPI; and then do your AWT-related things inside of\n a `jpype.setupGuiEnvironment` call on the main Python thread:\n\n ```python\n import jpype, scyjava\n scyjava.start_jvm()\n def hello():\n JOptionPane = scyjava.jimport('javax.swing.JOptionPane')\n JOptionPane.showMessageDialog(None, \"Hello world\")\n jpype.setupGuiEnvironment(hello)\n ```\n\n In which case, the `setupGuiEnvironment` call will block the main Python\n thread forever.\n",
"bugtrack_url": null,
"license": "The Unlicense",
"summary": "Supercharged Java access from Python",
"version": "1.10.0",
"project_urls": {
"documentation": "https://github.com/scijava/scyjava/blob/main/README.md",
"download": "https://pypi.org/project/scyjava/",
"homepage": "https://github.com/scijava/scyjava",
"source": "https://github.com/scijava/scyjava",
"tracker": "https://github.com/scijava/scyjava/issues"
},
"split_keywords": [
"java",
" maven",
" cross-language"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "0349a31c78a5b194fe17b041a6a3a2b99cdc664dfe7592159dae9952a7efea7f",
"md5": "25916c620e72d092bd2f95ae62a80354",
"sha256": "ee44e8cc9917ea12633b5871e0cb081928f3f241455270e24b1edf3cae1a9e7c"
},
"downloads": -1,
"filename": "scyjava-1.10.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "25916c620e72d092bd2f95ae62a80354",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.8",
"size": 31012,
"upload_time": "2024-06-11T16:50:04",
"upload_time_iso_8601": "2024-06-11T16:50:04.983701Z",
"url": "https://files.pythonhosted.org/packages/03/49/a31c78a5b194fe17b041a6a3a2b99cdc664dfe7592159dae9952a7efea7f/scyjava-1.10.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "556a2a65fcf6eb48537543a2e0a8465035495702daed999057c48909854a44ce",
"md5": "78fd5816561ef2128c2eb4986028ff45",
"sha256": "7f86e8637e8e79de56d643d978e83253ff38974a43d76579f3792d5e076d5681"
},
"downloads": -1,
"filename": "scyjava-1.10.0.tar.gz",
"has_sig": false,
"md5_digest": "78fd5816561ef2128c2eb4986028ff45",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.8",
"size": 47036,
"upload_time": "2024-06-11T16:50:06",
"upload_time_iso_8601": "2024-06-11T16:50:06.821595Z",
"url": "https://files.pythonhosted.org/packages/55/6a/2a65fcf6eb48537543a2e0a8465035495702daed999057c48909854a44ce/scyjava-1.10.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-06-11 16:50:06",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "scijava",
"github_project": "scyjava",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "scyjava"
}