4

I'm building a front-end for my company's internal tool kit. Half the tools are written in python and then the other half are written in several other scripting languages. So I'm building a front-end in java using swing. So far I can invoke python scripts through the following code:

public class Foo
{
    public static void main(String[] args)
    {
        try
        {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec("python foo.py");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            p.waitFor();
            String line = "";
            while (br.ready())
                System.out.println(br.readLine());

        }
        catch (Exception e)
        {
        String cause = e.getMessage();
        if (cause.equals("python: not found"))
            System.out.println("No python interpreter found.");
        }
    }
} 

Which works beautifully but if the python script encounters any errors it doesn't print them out. How can I ensure that it also prints out any errors that it has?

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Chris Maness
  • 1,682
  • 3
  • 22
  • 40

2 Answers2

5

The simple answer is to also read Process.getErrorStream.

The more complicated answer is that what you call Python likely refers to CPython which is just one implementation of the language. There is another implementation, Jython, which basically compiles Python into Java bytecode to be run on a JVM. This would allow tighter integration than simply invoking CPython via Java's Runtime.exec

P.S. Runtime.exec is sort of the old way of doing things. ProcessBuilder is often a much cleaner and more intuitive way of starting a sub-process in Java.

Tim Bender
  • 20,112
  • 2
  • 49
  • 58
  • The point of all this is to have very loose integration into the Java front end as the tools are always changing and evolving. Thanks for you solution though it's exactly what I needed. – Chris Maness Mar 20 '13 at 19:07
  • 1
    This incredibly old article is surprisingly relevant to your needs. http://www.javaworld.com/jw-12-2000/jw-1229-traps.html?page=1 – Tim Bender Mar 21 '13 at 22:46
0

The prevois answer is Ok,here is a suggestion that you shoud release any resources of Process,like:

        Process process = null;
    try{
        //xxxx
    }catch(xxx){

    }finally{
        if(process!=null){
            process.destroy();
        }
    }

The reason is that if you forgot to destroy process,the file handler involved would leak, you will got an IOException show too many open files finally.

BlackJoker
  • 3,099
  • 2
  • 20
  • 27