|
From: Christian P. <chr...@we...> - 2016-11-18 10:09:25
|
Hi,
I was wondering if there exists a way to terminate a script running an
endless loop. To clarify the problem I have attached some source code.
None of the tested methods stops the while loop of the main script:
public class PythonTest {
private static InteractiveInterpreter engine;
private static final String CODE = "import time\n" +
"\n" +
"while True:\n" +
" print('still there')\n" +
" time.sleep(1)\n" +
"";
private static final String TERMINATE = "import sys\n" +
"sys.exit()";
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - 10 * 1000 < start)
Thread.yield();
System.out.println(">>>>>>>>>>> Terminating");
// engine.getSystemState().callExitFunc();
// engine.getSystemState().exit();
// engine.interrupt(new
ThreadState(engine.getSystemState()));
execute(TERMINATE);
}
}).start();
engine = new InteractiveInterpreter();
engine.getSystemState().__setattr__("_jy_interpreter",
Py.java2py(engine));
engine.getSystemState().path.insert(0, Py.EmptyString);
execute(CODE);
System.out.println("---------- done");
}
private static void execute(String input) {
final PyObject code = Py.compile_command_flags(input, "(none)",
CompileMode.exec, new CompilerFlags(), true);
if (code == Py.None)
throw new RuntimeException("Could not compile code");
Py.exec(code, engine.getLocals(), null);
}
}
thanks
Christian
|