【问题标题】:How to use pyodide function more one times如何多次使用pyodide函数
【发布时间】:2021-10-29 14:51:14
【问题描述】:

我想运行函数来阻止表格的每一行。我想在加载 HTML 代码后执行此操作,我试试这个

<body>
    <script
      type="text/javascript"
      src="https://cdn.jsdelivr.net/pyodide/dev/full/pyodide.js"
    ></script>
    <script type="text/javascript">
        
      async function main(kw) {
        let pyodide = await loadPyodide({
          indexURL: "https://cdn.jsdelivr.net/pyodide/dev/full/",
        });
        
        pyodide.globals.set("mikw", kw);     
        await pyodide.loadPackage("micropip");
        await pyodide.runPythonAsync(`
            
        import micropip
        import js
        await micropip.install('snowballstemmer')
        import snowballstemmer
        stemmer = snowballstemmer.stemmer('english')
        
        div = js.document.createElement("div")
        div.innerHTML = stemmer.stemWords('Hello this my default text '.split())
        js.document.body.prepend(div)
        varP = js.document.getElementById('origen').textContent
        print(varP)
        salida = stemmer.stemWords(varP.split())
        print(salida)
        divSalida = js.document.createElement("div")
        div.innerHTML =salida
        salida = stemmer.stemWords(mikw.split())
        print(salida)

        `);
        
      } 
        
      main('This are the second text, I put this text on arguments function');
    </script>
    <div id="origen" >This text is inside of HTML element</div>
 </body>

输出是

['This', 'text', 'is', 'insid', 'of', 'HTML', 'element']
['This', 'are', 'the', 'second', 'text,', 'I', 'put', 'this', 'text', 'on', 'argument', 'function']

但我不能(或者我不知道)在加载 html 之后使用函数来阻止其他 kws,例如在加载 DOM 之后(获取我的 HTML 表的值并运行每个)

....      
<div id="origen" onclick="temp()">This text is inside of HTML element</div>
   <script>
     myNewkwStemm=main('other word');
     myNewkwStemm2=main('word2');
   </script>
</body>

【问题讨论】:

    标签: webassembly pyodide


    【解决方案1】:

    您通过在 main 函数中包含 loadPyodide 调用来多次加载 Pyodide,这会为您后续的 main 调用提供错误。将loadPyodide 移出main 应该可以解决问题:

    <script type="text/javascript">
      let initPyodide = loadPyodide({
        indexURL: "https://cdn.jsdelivr.net/pyodide/dev/full/",
      })
      async function main(kw) {
        let pyodide = await initPyodide
        // ... other code
      }
    

    jsfiddle

    此外,您可能不想依赖 pyodide.globals 来传递参数,因为您正在异步运行所有内容,这会导致竞争条件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多