Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
hinerm opened this issue May 2, 2024 · 2 comments

Comments

@hinerm
Copy link
Member

hinerm commented May 2, 2024

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
Copy link
Member Author

hinerm commented May 2, 2024

Originally reported here.

See jython/jython#327

@imagesc-bot
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants