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);
                  }

1 Answer 1

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

5
  • Thanks Nick. That was already commented in the code, I missed to remove it when I posted. Commented Apr 6, 2014 at 13:27
  • Ok, so you are still having trouble getting the output correct or was that the only problem?
    – Nick
    Commented Apr 6, 2014 at 13:32
  • Yes, I still have the issue. Commented Apr 6, 2014 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. javadb.com/… 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
    Commented Apr 6, 2014 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. Commented Dec 3, 2021 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.