【问题标题】:Import a javascript function in js2py在 js2py 中导入一个 javascript 函数
【发布时间】:2022-08-22 16:03:39
【问题描述】:

我有一个python文件:

import js2py
from js2py import require

js= \'\'\'
    function myfuntion(){
        var b = numar();
        return b;
    }
\'\'\'

a = js2py.eval_js(js)

print(a())

这只是一个例子。 \"js2py\" 必须调用来自不同 javascript 文件的函数。

javascript文件:

export function numar(){
    return 1; //return 1 if the checkbox is
}

如何将该函数导入 js2py?

  • js2py.translate_file(\'example.js\', \'example.py\') 之类的内容会与您的用例匹配吗?

标签: javascript python-3.x backend


【解决方案1】:

这仍然是 js2py 中的一个问题,此链接可能会对您有所帮助。 https://github.com/PiotrDabkowski/Js2Py/issues/123#issuecomment-866218046

解决这个问题的唯一方法是修改翻译文件。

# translate myfunction.js, numar.js files to python
import js2py

js2py.translate_file('numar.js', 'numar.py')
js2py.translate_file('myfunction.js', 'myfunction.py')
// myfunction.js
var numar = require("./numar");
function myfunction() {
  var b = numar();
  return b;
}
// numar.js
function numar(){
    return 1; //return 1 if the checkbox is
}
# then modify translated myfunction.py file like this
__all__ = ['myfunction']

# Don't look below, you will not understand this Python code :) I don't.

from js2py.pyjs import *
from numar import numar
# setting scope
var = Scope( JS_BUILTINS )
set_global_object(var)

# Code follows:
var.registers(['numar', 'myfunction'])
@Js
def PyJsHoisted_myfunction_(this, arguments, var=var):
    var = Scope({'this':this, 'arguments':arguments}, var)
    var.registers(['b'])
    var.put('b', var.get('numar')())
    return var.get('b')
PyJsHoisted_myfunction_.func_name = 'myfunction'
var.put('myfunction', PyJsHoisted_myfunction_)
var.put('numar', numar.numar)
pass
pass


# Add lib to the module scope
myfunction = var.to_python()
# import in your code
from myfunction import myfunction

print(myfunction.myfunction())

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 2019-03-01
    • 2019-03-06
    • 2018-06-21
    • 2019-10-13
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    相关资源
    最近更新 更多