简体   繁体   English

从Java调用python

[英]Invoking python from Java

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. 一半的工具是用python编写的,然后另一半是用其他几种脚本语言编写的。 So I'm building a front-end in java using swing. 所以我在使用swing构建java的前端。 So far I can invoke python scripts through the following code: 到目前为止,我可以通过以下代码调用python脚本:

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. 哪个工作得很漂亮,但如果python脚本遇到任何错误,它就不会打印出来。 How can I ensure that it also prints out any errors that it has? 如何确保它还打印出它有的任何错误?

The simple answer is to also read Process.getErrorStream . 简单的答案是还要读取Process.getErrorStream

The more complicated answer is that what you call Python likely refers to CPython which is just one implementation of the language. 更复杂的答案是你所谓的Python可能是指CPython,它只是该语言的一种实现。 There is another implementation, Jython, which basically compiles Python into Java bytecode to be run on a JVM. 还有另一个实现,Jython,它基本上将Python编译成Java字节码,以便在JVM上运行。 This would allow tighter integration than simply invoking CPython via Java's Runtime.exec 与只通过Java的Runtime.exec调用CPython相比,这将允许更紧密的集成

PS Runtime.exec is sort of the old way of doing things. PS Runtime.exec是一种旧的做事方式。 ProcessBuilder is often a much cleaner and more intuitive way of starting a sub-process in Java. ProcessBuilder通常是一种更清晰,更直观的方式来启动Java中的子流程。

The prevois answer is Ok,here is a suggestion that you shoud release any resources of Process,like: prevois的回答是好的,这里有一个建议,你应该释放任何进程资源,如:

        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. 原因是如果你忘了销毁进程,所涉及的文件处理程序会泄漏,你会得到一个IOException,最后显示太多打开的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM