0

I've a Java program to call a python script. I've used exec method. Please find the code snippet below:

Python program (which is to gather a portion of text from wikipedia), when run separately, gives me proper output. When called from Java, I'm not getting the complete output from python program.

I checked the status of BufferedReader Object using ready() method ( as explained here, and the code entered into infinite loop.

I think others also have faced similar problems-https://stackoverflow.com/a/20661352/3409074

Can anyone help me?

      public String enhanceData(String name,String entity) {
            String s = null;
            StringBuffer output = new StringBuffer();
            try{
                String command="python C://enhancer.py "+name+" "+entity;
                Process p = Runtime.getRuntime().exec(command);
                BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
                BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((s = stdInput.readLine()) != null) {

                    System.out.println(s);
                    output.append(s);
                  }
Community
  • 1
  • 1

1 Answers1

1

The while loop condition has actually already read a line so you are double reading it for every time in the loop.

while ((s = stdInput.readLine()) != null) {
    //s=stdInput.readLine();  <- don't need this
    System.out.println(s);
    output.append(s);
}

/Nick

Nick
  • 114
  • 5
  • Thanks Nick. That was already commented in the code, I missed to remove it when I posted. – user3409074 Apr 06 '14 at 13:27
  • Ok, so you are still having trouble getting the output correct or was that the only problem? – Nick Apr 06 '14 at 13:32
  • Yes, I still have the issue. – user3409074 Apr 06 '14 at 14:03
  • Ok, try to use the InputStream instead to read bytes. There's an example of it here. It's pretty much what you have in your program except for the InputStream instead of a reader. http://www.javadb.com/execute-external-program-with-runtime-and-process-classes/ It might be that you can use the reader, but have to call the waitFor method on the process to wait until it has finished (as done in the example). – Nick Apr 06 '14 at 15:15
  • Hey, could you please post the entire solution here? I am facing the same issue, and the accepted answer isn't helping me. If someone could post the entire solution that would be helpful. – Ananth Kamath Dec 03 '21 at 06:58