scyjava


Namescyjava JSON
Version 1.9.1 PyPI version JSON
download
home_page
SummarySupercharged Java access from Python
upload_time2023-07-07 23:09:47
maintainer
docs_urlNone
author
requires_python>=3.7
licenseThe 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.add_option('-Djava.awt.headless=true')
>>> 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

    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.

    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) -> bool
        Return whether the given data object is a Java array.

    is_jvm_headless() -> bool
        Return true iff Java is running in headless mode.

        :raises 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.
        :returns: The newly allocated array

    jclass(data)
        Obtain a Java class object.

        :param data: The object from which to glean the class.
        Supported types include:
        A. Name of a class to look up, analogous to
        Class.forName("java.lang.String");
        B. A jpype.JClass object analogous to String.class;
        C. A jpype.JObject instance analogous to o.getClass().
        :returns: A java.lang.Class object, suitable for use with reflection.
        :raises 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.
        :returns: 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.
        :returns: 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.
        :returns: 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 should return 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.

    shutdown_jvm() -> None
        Shutdown 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.

    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:
                        ['-Djava.awt.headless=true', '-Xmx4g']

    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.
        :returns: A corresponding Java object with the same contents.
        :raises 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.
        :returns: A corresponding Python object with the same contents.
        :raises 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.add_option('-Djava.awt.headless=true')
    ```

    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": "",
    "name": "scyjava",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "java,maven,cross-language",
    "author": "",
    "author_email": "SciJava developers <ctrueden@wisc.edu>",
    "download_url": "https://files.pythonhosted.org/packages/24/d9/14972ae969846cca0904016e9ca5f61a561c38fcf112df832e076694a0bf/scyjava-1.9.1.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.add_option('-Djava.awt.headless=true')\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    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    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) -> 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        :raises 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        :returns: The newly allocated array\n\n    jclass(data)\n        Obtain a Java class object.\n\n        :param data: The object from which to glean the class.\n        Supported types include:\n        A. Name of a class to look up, analogous to\n        Class.forName(\"java.lang.String\");\n        B. A jpype.JClass object analogous to String.class;\n        C. A jpype.JObject instance analogous to o.getClass().\n        :returns: A java.lang.Class object, suitable for use with reflection.\n        :raises 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        :returns: 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        :returns: 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        :returns: 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,\n        with each dot-separated digit as one element.\n        Characters in the version string beyond only\n        numbers and dots are ignored, in line\n        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,\n        this function should return 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    shutdown_jvm() -> None\n        Shutdown 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    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: List of options to pass to the JVM. For example:\n                        ['-Djava.awt.headless=true', '-Xmx4g']\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: The Python object to convert.\n        :param hints: An optional dictionary of hints, to help scyjava\n                      make decisions about how to do the conversion.\n        :returns: A corresponding Java object with the same contents.\n        :raises 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: The Java object to convert.\n        :param gentle: If set, and the type cannot be converted, leaves\n                       the data alone rather than raising a TypeError.\n        :returns: A corresponding Python object with the same contents.\n        :raises TypeError: 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.add_option('-Djava.awt.headless=true')\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.9.1",
    "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": "6993ffa551855733b51cd99fcccda9310d1e84e26871d6844cd5a90e3299cd6f",
                "md5": "d42e10272a227e6cb9a0ca0b8f51f216",
                "sha256": "92de163eab66a14eebadfd8c00a0484da51689301ea9c7145a1533a3f29ecf4d"
            },
            "downloads": -1,
            "filename": "scyjava-1.9.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "d42e10272a227e6cb9a0ca0b8f51f216",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 27909,
            "upload_time": "2023-07-07T23:09:45",
            "upload_time_iso_8601": "2023-07-07T23:09:45.372482Z",
            "url": "https://files.pythonhosted.org/packages/69/93/ffa551855733b51cd99fcccda9310d1e84e26871d6844cd5a90e3299cd6f/scyjava-1.9.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "24d914972ae969846cca0904016e9ca5f61a561c38fcf112df832e076694a0bf",
                "md5": "14d22a05ea51a3a203fbb852d61f00e3",
                "sha256": "b305327386e51d7f5af984c42793fcc5f89e0a82d2e6ecb45f5fe9467fc0cbe3"
            },
            "downloads": -1,
            "filename": "scyjava-1.9.1.tar.gz",
            "has_sig": false,
            "md5_digest": "14d22a05ea51a3a203fbb852d61f00e3",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 42650,
            "upload_time": "2023-07-07T23:09:47",
            "upload_time_iso_8601": "2023-07-07T23:09:47.175184Z",
            "url": "https://files.pythonhosted.org/packages/24/d9/14972ae969846cca0904016e9ca5f61a561c38fcf112df832e076694a0bf/scyjava-1.9.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-07 23:09:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "scijava",
    "github_project": "scyjava",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "scyjava"
}
        
Elapsed time: 0.09548s