使用Beakerx自定义魔术

时间:2018-07-25 21:27:56

标签: beaker beaker-notebook

我创建了一个自定义的Magic命令,旨在以编程方式生成一个火花查询。这是我的类中实现MagicCommandFunctionality的相关部分:

MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam) {    

    // get the string that was entered:
    String input = magicCommandExecutionParam.command.substring(MAGIC.length())

    // use the input to generate a query
    String generatedQuery =  Interpreter.interpret(input)

    MIMEContainer result = Text(generatedQuery);
    return new MagicCommandOutput(MagicCommandOutcomeItem.Status.OK, result.getData().toString());
}

这很出色。它返回我生成的命令。 (作为文字)

我的问题是-我如何强迫笔记本对单元格中的值进行评估我的猜测是涉及到SimpleEvaluationObject和TryResult,但是我可以找不到任何使用示例

我可能不是想要创建MagicCommandOutput,而是要内核为我创建一个。我看到KernelMagicCommand具有可以执行此操作的execute方法。有人有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好的,我找到了一种方法。这是我的解决方案:
您可以向当前的kernelManager询问您感兴趣的内核,
然后调用PythonEntryPoint.evaluate。似乎可以完成工作!

@Override     MagicCommandOutcomeItem execute(MagicCommandExecutionParam magicCommandExecutionParam){

String input = magicCommandExecutionParam.command.substring(MAGIC.length() + 1)
// this is the Scala code I want to evaluate:
String codeToExecute = <your code here>

KernelFunctionality kernel = KernelManager.get()
PythonEntryPoint pep = kernel.getPythonEntryPoint(SCALA_KERNEL)
pep.evaluate(codeToExecute)
pep.getShellMsg()

List<Message> messages = new ArrayList<>()
//until there are messages on iopub channel available collect them into response
    while (true) {
        String iopubMsg = pep.getIopubMsg()
        if (iopubMsg == "null") break
        try {
            Message msg = parseMessage(iopubMsg) //(I didn't show this part)
            messages.add(msg)
            String commId = (String) msg.getContent().get("comm_id")
            if (commId != null) {
                kernel.addCommIdManagerMapping(commId, SCALA_KERNEL)
            }
        } catch (IOException e) {
            log.error("There was an error: ${e.getMessage()}")
            return new MagicKernelResponse(MagicCommandOutcomeItem.Status.ERROR, messages)
        }
    }
    return new MagicKernelResponse(MagicCommandOutcomeItem.Status.OK, messages)
}