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();
    }
5
  • 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. Commented Sep 5, 2014 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 :) Commented Sep 5, 2014 at 11:43
  • You're Welcome - Abhijeet Panwar Commented Sep 5, 2014 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(). Commented Sep 5, 2014 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 :( Commented Sep 5, 2014 at 12:42

0

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.