1

I have a python file:

import js2py
from js2py import require

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

a = js2py.eval_js(js)

print(a())

This is just an example. The "js2py" must call a function from a different javascript file.

The javascript file:

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

How can I import that function into the js2py?

2 Answers2

3

There is a new alternative to js2py called PythonMonkey which lets you import JavaScript files directly from Python and execute them.

https://github.com/Distributive-Network/PythonMonkey

JavaScript numar.js file:

module.exports = function numar(){
    return 1; //return 1 if the checkbox is
}

Python main.py file:

import pythonmonkey as pm
numar = pm.require('./numar')

print(numar()) # this outputs "1.0"
Will Pringle
  • 121
  • 2
1

This is still an issue in js2py and this link may help you. https://github.com/PiotrDabkowski/Js2Py/issues/123#issuecomment-866218046

The only way to solve this is to modify translated file.

# 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())

You can find the code here.

https://github.com/lacmansoftware/python-js2py-require-solution