eclipse插件可以调用外部python脚本吗?

时间:2014-01-22 21:32:33

标签: java eclipse eclipse-plugin

我的目的是开发一个eclipse插件(我将解释为什么我会坚持使用eclipse插件。),它将在特定位置执行python脚本(比如C:\ MyProject \ testscript.py)。

我有兴趣从那些已经尝试过类似方法的人那里得到答案,看看这种方法是否有效。

为什么选择Eclipse插件?
我正在尝试收听服务器的通知。虽然服务器公开了普通的Java API,但是监听机制不是作为普通的java api提供的。但是使用服务器提供的eclipse插件,我可以在eclipse UI中看到通知。

2 个答案:

答案 0 :(得分:1)

我建议尝试使用Jython从Java(Eclipse插件)桥接到Python。另请参阅Calling Python in Java?(可能还有Invoking python from Java和/或How to execute Python script from Java?

答案 1 :(得分:1)

是的,有可能

示例代码段

// Python脚本“test.py”从eclipse插件执行

公共类SampleHandler扩展了AbstractHandler {

/**
 * The constructor.
 */
public SampleHandler() {
}

/**
 * the command has been executed, so extract extract the needed information
 * from the application context.
 */
public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
    MessageDialog.openInformation(
            window.getShell(),
            "First",
            "Hello, Eclipse world");

    try
    {
        Runtime r = Runtime.getRuntime();

        String pythonScriptPath = "D:\\python-samples\\test.py";
        Process p = r.exec("python " + pythonScriptPath);

        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        while((line = bfr.readLine()) != null) {
        // display each output line form python script
        System.out.println(line);
    }
    }
    catch (Exception e)
    {
    String cause = e.getMessage();
    if (cause.equals("python: not found"))
        System.out.println("No python interpreter found.");
    }
    return null;
}

}