Search code examples
pythonspringspring-mvcmodel-view-controllerpyomo

How to execute a pyomo model script inside Spring?


I have a web interface built with Spring and I want to execute the command "python file.py" from it.
The main problem is that inside the file.py there is a pyomo model that is supposed to give some output. I can execute a python script if it's a simple print or something, but the pyomo model is completely ignored.

What could be the reason?

Here is the code I wrote in the controller to execute the call:

 @PostMapping("/execute")
    public void execute(@ModelAttribute("component") @Valid Component component, BindingResult result, Model model) {

        Process process = null;
        //System.out.println("starting!");
        try {
            process = Runtime.getRuntime().exec("python /home/chiara/Documents/GitHub/Pyomo/Solver/test/sample.py");
            //System.out.println("here!");
        } catch (Exception e) {
            System.out.println("Exception Raised" + e.toString());
        }
        InputStream stdout = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                System.out.println("stdout: " + line);
            }
        } catch (IOException e) {
            System.out.println("Exception in reading output" + e.toString());
        }
    }

Solution

  • Update: I found that what I was missing was that I didn't check where the code run.
    So be sure to do so and eventually move the input files (if you have any) in the directory where python is executing, otherwise the script can't find them and elaborate them.

    You can use

    cwd = os.getcwd()
    

    to check the current working directory of a process. Another possibility is to redirect the stderr on the terminal or in a log file, because from the Server terminal you won't see anything even if there are errors.

    The code posted in the question is the correct way to invoke a bash command from java.