|
| 1 | +""" |
| 2 | +Test the enable_python_scripting function, and subsequent use of |
| 3 | +the SciJava Python script language (org.scijava:scripting-python). |
| 4 | +
|
| 5 | +As a side effect, this script also tests Maven dependency resolution. |
| 6 | +""" |
| 7 | + |
| 8 | +import sys |
| 9 | +import scyjava |
| 10 | + |
| 11 | +scyjava.config.endpoints.extend([ |
| 12 | + "org.scijava:scijava-common:2.94.2", |
| 13 | + "org.scijava:scripting-python:MANAGED" |
| 14 | +]) |
| 15 | + |
| 16 | +# Create minimal SciJava context with a ScriptService. |
| 17 | +Context = scyjava.jimport("org.scijava.Context") |
| 18 | +ScriptService = scyjava.jimport("org.scijava.script.ScriptService") |
| 19 | +# HACK: Avoid "[ERROR] Cannot create plugin" spam. |
| 20 | +WidgetService = scyjava.jimport("org.scijava.widget.WidgetService") |
| 21 | +ctx = Context(ScriptService, WidgetService) |
| 22 | + |
| 23 | +# Enable the Python script language. |
| 24 | +scyjava.enable_python_scripting(ctx) |
| 25 | + |
| 26 | +# Assert that the Python script language is available. |
| 27 | +ss = ctx.service("org.scijava.script.ScriptService") |
| 28 | +lang = ss.getLanguageByName("Python") |
| 29 | +assert lang is not None and "Python" in lang.getNames() |
| 30 | + |
| 31 | +# Construct a script. |
| 32 | +script = """ |
| 33 | +#@ String name |
| 34 | +#@ int age |
| 35 | +#@output String statement |
| 36 | +statement = f"Hello, {name}! In one year you will be {age + 1} years old." |
| 37 | +"A wild return value appears!" |
| 38 | +""" |
| 39 | +StringReader = scyjava.jimport("java.io.StringReader") |
| 40 | +ScriptInfo = scyjava.jimport("org.scijava.script.ScriptInfo") |
| 41 | +info = ScriptInfo(ctx, "script.py", StringReader(script)) |
| 42 | +info.setLanguage(lang) |
| 43 | + |
| 44 | +# Run the script. |
| 45 | +future = ss.run(info, True, "name", "Chuckles", "age", 13) |
| 46 | +try: |
| 47 | + module = future.get() |
| 48 | + outputs = module.getOutputs() |
| 49 | + statement = outputs["statement"] |
| 50 | + return_value = module.getReturnValue() |
| 51 | +except Exception as e: |
| 52 | + sys.stderr.write("-- SCRIPT EXECUTION FAILED --\n") |
| 53 | + trace = scyjava.jstacktrace(e) |
| 54 | + if trace: |
| 55 | + sys.stderr.write(f"{trace}\n") |
| 56 | + raise e |
| 57 | + |
| 58 | +assert statement == "Hello, Chuckles! In one year you will be 14 years old." |
| 59 | +assert return_value == "A wild return value appears!" |
0 commit comments