1

I have written a code to call a python script through java,I have tried it using both Runtime.exec() and process builder but by both the ways I am facing same problem.

My code is :

 Process pr=Runtime.getRuntime().exec("/usr/bin/python /home/abhijeet/delete.py");
 pr.waitFor();
 System.out.println("----- will read ouput now -----");

 BufferedReader br1=new BufferedReader(new InputStreamReader(pr.getInputStream()));
 String line;
 System.out.println("reached pont 1");

 while ((line=br1.readLine())!=null) 
 {
        System.out.println("inside while");
        System.out.println("line--"+line);
 }
 System.out.println("outside while");

I have added many sop's to know flow of the program ,but none of my sop is called ,Probable reason for this is , that pr.waitfor() keeps waiting.If I remove that my br1.readline() returns null and 'reached point 1' and 'outside while' message is printed.Which means that my script is not being called. Can someone figure it out that what I have done wrong in it?

My python scipt code is an interactive one , Code:

 #!/usr/bin/python
print 'Enter numbers'
a  = raw_input()
print 'a is',a
b  = raw_input()
print 'b is',b
c  = raw_input()
print 'c is',c
d  = raw_input()
print 'd is',d
e  = raw_input()
print 'e is',e
f  = raw_input()
print 'f is',f
g  = raw_input()
print 'g is',g
h  = raw_input()
print 'h is',h
print 'Sum is', int(a)+int(b)+int(c)+int(d)+int(e)+int(f)+int(g)+int(h)
print 'NOW IT COMPLETES'
Abhijeet Panwar
  • 1,837
  • 3
  • 26
  • 48
  • 2
    Consider using Jython, that'll be a much easier way to integrate Python with Java. – Óscar López Jul 23 '14 at 03:11
  • I will try ,But want to find out my error in this code. – Abhijeet Panwar Jul 23 '14 at 03:12
  • I ran your code with a dummy python file, and worked fine for me. Are you sure you are not getting the first print "----- will read ouput now -----" ? – gaganbm Jul 23 '14 at 05:48
  • @gaganbm yes ,I am not getting the first line.Should I post python script also? It's a interactive one ,and I am have not worked with python much. – Abhijeet Panwar Jul 23 '14 at 05:57
  • @gaganbm I have added python script in question. – Abhijeet Panwar Jul 23 '14 at 06:02
  • 2
    That pretty much explains. Your python script is expecting some user inputs. And the process never completes, as the script proceeds. If you use a script, w/o any user interaction, this will work. If you must need user input in your script, you need to get pr.getOutputStream, like you do for pr.getInputStream. You can refer here : http://stackoverflow.com/questions/3643939/java-process-with-input-output-stream – gaganbm Jul 23 '14 at 08:53
  • @gaganbm : but atleast my 'Enter numbers' message should be printed at outputstream , right? – Abhijeet Panwar Jul 24 '14 at 06:29

0 Answers0