I have done quite a bit of research on this, and unfortunately have been unable to find an answer that is suitable to the problem I'm currently having.
My question isn't as simple as "how do I run a python script from Java," to which there exists at least 10 threads all containing the same answer. I understand how to do that. My problem is as follows:
I have a .py file (gui.py
) which looks something like this:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import copy
import math
import numpy as np
class GUI(object):
...
...
...
if __name__ == '__main__':
GUI.run()
This gui is an interactive matplotlib plot on which users draw stuff. Details aren't important - bottom line is the script runs for as long as the matplotlib window is open.
Now, I'm building a Java app on the side, and there's a button which when clicked creates a Java Process
object which will call the script. I know from reading other posts that PIPE cannot be called from the java runtime, so I've created a .sh
file which wraps around this python script.
shell.sh
:
#!/bin/sh
python /mypath/to/the/gui.py
The Java to call the shell script:
view.getLaunchGuiButton().addActionListener((e) -> {
try {
String[] prcArgs = new String[] { "/mypath/to/shell.sh" };
Process proc = Runtime.getRuntime().exec(prcArgs);
} catch (IOException e1 ) {
e1.printStackTrace();
}
});
The shell script is correct - when I run it from the terminal correctly everything functions as normal.
I know that the Java is indeed executing the shell script, and calling the python script. There are no errors. I didn't set up any BufferedReader
because there's nothing to read - I just need to GUI to open. I believe that the problem is that once the shell is executed, the "terminal" so-to-speak which is opened by the Runtime
is immediately closed, hence it kills the python script and therefore the GUI.
My question is, how do I keep the Runtime
from simply running and immediately killing the python script (AKA closing the terminal)?
Things I've already done:
chmod +x ../../shell.sh
nohup /call/python/here &
in the shell script. Didn't work.ProcessBuilder
instead of the Runtime
. No difference.Any ideas? Thank you all in advance.
From the Java Button listner I exec-ed xterm:
try {
Process p = Runtime.getRuntime().exec("xterm");
Thread.sleep(1500);
} catch (IOException e1 ) {
e1.printStackTrace();
}
In ~/.bashrc
I added my command which starts my Python script with GUI:
if [[ -z "$XTERM_ONCE" ]]
then
export XTERM_ONCE=$(date)
cd /home/qswadey/path/to/py/script/
python3 pyscript_with_GUI.py
fi
The Python GUI shows up and continues...
The idea of running a command on xterm startup, for all xterm is sourced from this thread: How to run a command on the startup of an xterm?
The Thread.sleep
is just for holding the xterm for some time to see output of short command, however the xterm remains running in interactive mode