开发PyCharm(2019.3.3)插件:如何获取Tool Window中的运行结果?
获取PyCharm 2019.3.3插件中Tool Window运行结果的实现方案
- 定位目标Tool Window的控制台组件
PyCharm的运行结果默认在Run Tool Window中,可通过RunContentManager获取已加载的控制台实例:
RunContentManager contentManager = RunContentManager.getInstance(project); for (RunContentDescriptor descriptor : contentManager.getAllDescriptors()) { ConsoleView consoleView = descriptor.getConsoleView(); if (consoleView != null) { // 可通过descriptor的名称匹配目标控制台 if ("目标运行任务名称".equals(descriptor.getDisplayName())) { String output = getConsoleOutput(consoleView); // 对获取到的输出做后续处理 } } }
- 提取控制台的输出内容
在2019.3.3版本中,ConsoleView的实际实现类为TextConsoleViewImpl,可通过其关联的Document获取全部文本:
private String getConsoleOutput(ConsoleView consoleView) { if (consoleView instanceof TextConsoleViewImpl) { TextConsoleViewImpl textConsole = (TextConsoleViewImpl) consoleView; Document document = textConsole.getEditor().getDocument(); return document.getText(); } return ""; }
- 实时监听控制台输出(可选)
如果需要实时捕获新增的运行结果,可注册ConsoleListener:
consoleView.addConsoleListener(new ConsoleListener() { @Override public void onTextAdded(@NotNull ConsoleView consoleView, @NotNull String text) { // text为新增的输出内容,在此处处理 } });
内容的提问来源于stack exchange,提问作者Cornar
相关产品推荐
相关产品推荐

