3

编辑:谷歌集团帖子

我正在和Brython一起玩。

我试图弄清楚如何从 JavaScript 执行 Brython 代码。

http://www.brython.info/static_doc/en/jsobjects.html <-- 这看起来像相关的文档页面,但似乎缺少从 JavaScript 调用 Brython 函数的示例。

对于我的具体情况,我正在听 MIDI 事件(使用https://github.com/cwilso/WebMIDIAPIShim

我希望执行 Brython 代码以响应收到的 MIDI 事件。

目前我正在尝试:

function myMIDIMessagehandler( event ) 
{
    if( brythonListener != null )
        brythonListener( event );

和 Brython 代码:

<script type="text/python3">

from browser import document as doc, window, html

def foo(event):
    print("BRYTHON!" + event);

window.brythonListener = foo

</script>

但是当我在我的 MIDI 键盘上按下一个音符时,我得到:

在此处输入图像描述

我不知道如何处理这个错误,而且我完全不确定这种方法是否合理。

4

1 回答 1

5

已经一年了,所以我想你很久以前就解决了这个问题,但是你的方法原则上是正确的,我也是这样做的,当你映射它时它可以工作,就像你使用 window.js_func = py_func 一样。以下是我目前在 chromium / firefox 上使用的代码中的一些相关位:

<!-- Bottom of HTML.. -->
<script type="text/javascript">
var jv_funcs = {
    openfile:function(iptElement, fileType){
        // some file opening code then a call back to python
        open_file(reader.result, fileType);
    }
};
</script>
<script type="text/python3" src="src/pythonscript.py"></script>


# separate python script in my case 'pythonscript.py'
def open_file(fileContent, fileType):
    # show the file in the dom..

def open_clicked():
    window.jv_funcs.openfile(document["idOpen"], "fileType")


window.open_file = open_file
document["btnOpen"].bind("click", open_clicked)

需要知道的是,如果您使用 window.console.log(event),您将把事件作为一个对象返回,您可以从开发工具中进行探索。另一方面,打印将其展平为纯文本。

一个更大的问题可能是,使用 Brython 找出某些类型错误的原因可能非常棘手(尽管所有对 Brython 的尊重,它非常棒并且效果很好)。

可以更轻松地解决此类问题的一件事是源映射。我最近将一个个人项目从 Brython 转移到了 Transcrypt 发现 Transcrypt 的源映射支持有助于隔离错误原因。如此之多,以至于我没有尝试增量执行,而是大胆地编译了 python 源代码并一一跟进错误,直到一切正常(python 部分大约 2700 行)。在另一个方向上,这对我来说是不可能的,但对于了解 Brython 内部结构的人来说可能不是。

于 2016-07-21T04:26:40.570 回答