使用Py4J从python打开Eclipse编辑器

时间:2014-09-26 16:56:19

标签: python eclipse py4j

我试图从我的python程序中打开Eclipse编辑器中的文件。

以下是使用Java执行此操作的示例:

import java.io.File;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.IDE;

File fileToOpen = new File("externalfile.xml");

if (fileToOpen.exists() && fileToOpen.isFile()) {
    IFileStore fileStore = EFS.getLocalFileSystem().getStore(fileToOpen.toURI());
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        IDE.openEditorOnFileStore( page, fileStore );
    } catch ( PartInitException e ) {
        //Put your exception handler here if you wish to
    }
} else {
    //Do something if the file does not exist
}

我尝试使用Py4j从python中使用此API。

from py4j.java_gateway import JavaGateway, java_import

gateway = JavaGateway()
jvm = gateway.jvm

java_import(jvm, 'org.eclipse.core.filesystem.EFS')
java_import(jvm, 'org.eclipse.ui.PlatformUI')

fileToOpen = jvm.java.io.File('c:/test.txt')

fileStore = jvm.org.eclipse.core.filesystem.EFS.getLocalFileSystem().getStore(fileToOpen.toURI());

这很好用。但我已经堆积了page

page = jvm.org.eclipse.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

我在这里没有。看起来Rudolf Widmann已经发布了这个问题的答案here。所以java解决方案将是:

Display.getDefault().asyncExec(new Runnable() {
    @Override
    public void run() {
        IWorkbenchWindow iw = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
    }
});

但我怎么能从python中做到这一点?如何用Py4j实现它?

1 个答案:

答案 0 :(得分:0)

您是否尝试实施Runnable interface in Python?

class PythonRunner(object):
    def __init__(self, gateway):
        self.gateway = gateway
        self.iw

    def run(self):
        self.iw = gateway.jvm.org.eclipse.ui.PlatformUI.getWorkbench().getActiveWorkbenchWindow()

    class Java:
        implements = ['java.lang.Runnable']

gateway = JavaGateway(start_callback_server=True)
runner = PythonRunner(gateway)
gateway.jvm.org.eclipse.swt.widgets.Display.getDefault().asyncExec(runner)
# Replace with a synchronization primitive
time.sleep(2) 
page = runner.iw.getActivePage()