0

I want to run a python file that can run AWS CloudFormation template using JAVA. I am passing python file in JAVA code. When I run the JAVA code it pauses at the following state:

compile-single:

run-single:

If i run the Python file from terminal it works perfectly.

Java Code:

private void RunPythonActionPerformed(java.awt.event.ActionEvent evt) {                                          
    String pythonScriptPath = "path to python file";
    String[] cmd = new String[2];
    cmd[0] = "python"; // check version of installed python: python -V
    cmd[1] = pythonScriptPath;
    // create runtime to execute external command
    Runtime rt = Runtime.getRuntime();
    Process pr = null;
    try {
        pr = rt.exec(cmd);
        // retrieve output from python script
    } catch (IOException ex) {
        Logger.getLogger(Page2.class.getName()).log(Level.SEVERE, null, ex);
    }

BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
    try {
        while((line = bfr.readLine()) != null) {
        // display each output line form python script
        System.out.println(line);
        }        
        // TODO add your handling code here:
    } catch (IOException ex) {
        Logger.getLogger(Page2.class.getName()).log(Level.SEVERE, null, ex);
    }
}
  • Use ProcessBuilder to start a new process. You may find this post helpful. https://stackoverflow.com/questions/10097491/call-and-receive-output-from-python-script-in-java – piy26 Jun 20 '18 at 10:13

1 Answers1

0

Provide path to your source file at <complete path to your python source file> Copying working code for you. For me output is Python 3.6.5

package com.samples;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessBuilderSample {

    public static void main(String [] args) throws IOException {
        RunPythonActionPerformed();
    }

    private static void RunPythonActionPerformed() throws IOException {                                          
        String pythonScriptPath = "python -V";
        Process p = Runtime.getRuntime().exec(pythonScriptPath);

        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        try {
            while((line = bfr.readLine()) != null) {
                // display each output line form python script
                System.out.println(line);
            }        
            // TODO add your handling code here:
        } catch (IOException ex) {
        }
    }
}
piy26
  • 1,574
  • 11
  • 21