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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
This incredibly old article is surprisingly relevant to your needs. javaworld.com/jw-12-2000/jw-1229-traps.html?page=1
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.

Comments

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.