Skip to content

Commit f55d40f

Browse files
Fix python scripting to allow global imports and added testfile
1 parent d1583a1 commit f55d40f

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed

src/scyjava/_script.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,8 @@ def apply(self, arg):
9191
# Last statement looks like an expression. Evaluate!
9292
last = ast.Expression(block.body.pop().value)
9393

94-
_globals = {}
94+
_globals = {name: module for name, module in sys.modules.items() if name != '__main__'}
95+
9596
exec(
9697
compile(block, "<string>", mode="exec"), _globals, script_locals
9798
)

tests/it/script_scope.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
Test the enable_python_scripting function, but here explictly testing import scope for declared functions.
3+
"""
4+
5+
import sys
6+
7+
import scyjava
8+
9+
scyjava.config.endpoints.extend(
10+
["org.scijava:scijava-common:2.94.2", "org.scijava:scripting-python:MANAGED"]
11+
)
12+
13+
# Create minimal SciJava context with a ScriptService.
14+
Context = scyjava.jimport("org.scijava.Context")
15+
ScriptService = scyjava.jimport("org.scijava.script.ScriptService")
16+
# HACK: Avoid "[ERROR] Cannot create plugin" spam.
17+
WidgetService = scyjava.jimport("org.scijava.widget.WidgetService")
18+
ctx = Context(ScriptService, WidgetService)
19+
20+
# Enable the Python script language.
21+
scyjava.enable_python_scripting(ctx)
22+
23+
# Assert that the Python script language is available.
24+
ss = ctx.service("org.scijava.script.ScriptService")
25+
lang = ss.getLanguageByName("Python")
26+
assert lang is not None and "Python" in lang.getNames()
27+
28+
# Construct a script.
29+
script = """
30+
#@ int age
31+
#@output String cbrt_age
32+
import math
33+
34+
def calculate_cbrt(age):
35+
return round(math.cbrt(age))
36+
37+
cbrt_age = calculate_cbrt(age)
38+
# cbrt_age = round(math.cbrt(age))
39+
f"The rounded cube root of my age is {cbrt_age}"
40+
"""
41+
StringReader = scyjava.jimport("java.io.StringReader")
42+
ScriptInfo = scyjava.jimport("org.scijava.script.ScriptInfo")
43+
info = ScriptInfo(ctx, "script.py", StringReader(script))
44+
info.setLanguage(lang)
45+
46+
# Run the script.
47+
future = ss.run(info, True, "age", 13)
48+
try:
49+
module = future.get()
50+
outputs = module.getOutputs()
51+
statement = outputs["cbrt_age"]
52+
return_value = module.getReturnValue()
53+
except Exception as e:
54+
sys.stderr.write("-- SCRIPT EXECUTION FAILED --\n")
55+
trace = scyjava.jstacktrace(e)
56+
if trace:
57+
sys.stderr.write(f"{trace}\n")
58+
raise e
59+
60+
assert return_value == "The rounded cube root of my age is 2"
61+
assert statement == "2"

0 commit comments

Comments
 (0)