4

I am trying to run a python script using Apache Commons exec.I need to pass some values to python script as python script in an interactive one.How to do it?

My attempt was to set values in parent process's input stream.But it's not working for me.

My code so far:

String line = "python /home/abhijeet/test.py";

    CommandLine cmdLine = CommandLine.parse(line);

    byte buf[]="4".getBytes();

    InputStream io=new ByteArrayInputStream(buf);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    PumpStreamHandler streamhandler=new PumpStreamHandler(System.out,System.err,io);



    DefaultExecutor executor = new DefaultExecutor();

    executor.setStreamHandler(streamhandler); 

    executor.execute(cmdLine, resultHandler);



    try
    {
        resultHandler.waitFor();
    }

    catch (InterruptedException e) 
    {
        System.out.println("yo errior");
        e.printStackTrace();
    }
Abhijeet Panwar
  • 1,837
  • 3
  • 26
  • 48
  • According to the Apache documentation i guess u need to use, setProcessInputStream(OutputStream os): "Set the OutputStream by means of which input can be sent to the process.", write your bytes to an outputstream and call this function. – BatScream Sep 05 '14 at 11:36
  • @BatScream : I tried that before your answer to that question but even that did't work.It worked but It waits for me to enter values into console and if I will enter that value to console then it works fine.I don't want that and thanks for the help :) – Abhijeet Panwar Sep 05 '14 at 11:43
  • You're Welcome - Abhijeet Panwar – BatScream Sep 05 '14 at 12:07
  • @BatScream: Can you check it once? I am able to send first value but don't know that how to send rest of the values as I can't write multiple values by using io.write(). – Abhijeet Panwar Sep 05 '14 at 12:35
  • @BatScream : I tried OutputStream os=new ByteArrayOutputStream(); os.write("5".getBytes()); os.flush(); streamhandler.setProcessInputStream(os); code after creating stream handler.But it does't work :( – Abhijeet Panwar Sep 05 '14 at 12:42

0 Answers0