scijava / scripting-jython

JSR-223-compliant Jython scripting plugin
http://imagej.net/Jython_Scripting
BSD 2-Clause "Simplified" License
6 stars 5 forks source link

__file__ is not set correctly in subsequent script executions on the same thread #13

Open hinerm opened 2 months ago

hinerm commented 2 months ago

Given the following script:

final String script = "#@output String res\n" + "import os\n" + "res = os.path.dirname(os.path.abspath(__file__)) + __file__\n";
for (int i =0; i<5; i++) {
    final ScriptModule m = scriptService.run("add" + i + ".py", script, true).get();
    final Object result = m.getInfo().getLanguage().decode(m.getOutput("res"));
    System.out.println(result);
}

the __file__ variable will either: a) be set appropriately if this is the first time the script was run on a particular thread, or b) be unset, causing the script to fail.

The ScriptModule passes the file name to the engine. In Jython, this file name gets picked up in the PyScriptEngine. In the pathological case, this __file__ value is lost here

This does not seem to be a core problem with the interpreter, e.g. reuse of an existing interpreter within a thread produces appropriate output:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine pyEngine = mgr.getEngineByName("jython");
final String script = "print __file__\n";
for (int i=0; i<5; i++) {
    pyEngine.put(ScriptEngine.FILENAME, "hello" + i +".py");
    pyEngine.eval(script);
}

However, in our case, a new ScriptEngine instance (and interpreter instance) is created for each execution, whether it's within the same thread or not. If we modify the previous script to do the same, we can reproduce the error:

ScriptEngineManager mgr = new ScriptEngineManager();
final String script = "print __file__\n";
for (int i=0; i<5; i++) {
    ScriptEngine pyEngine = mgr.getEngineByName("jython");
    pyEngine.put(ScriptEngine.FILENAME, "hello" + i +".py");
    pyEngine.eval(script);
}

So this is either a bug in jython, or a misuse of the script engine on our part.

hinerm commented 2 months ago

Originally reported here.

See https://github.com/jython/jython/issues/327

imagesc-bot commented 2 months ago

This issue has been mentioned on Image.sc Forum. There might be relevant details there:

https://forum.image.sc/t/calling-executing-file-variable-3-times-in-jython-script-will-cause-an-error/95704/2