paint-brush
How to Call a JavaScript Function from Python Codeby@willp
4,012 reads
4,012 reads

How to Call a JavaScript Function from Python Code

by WillAugust 3rd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Run JavaScript Functions In Python with PythonMonkey! 🐍🐒
featured image - How to Call a JavaScript Function from Python Code
Will HackerNoon profile picture

This post will demonstrate how to execute JavaScript in Python using the PythonMonkey library for Python.

Refer to the PythonMonkey docs for more advanced features: https://docs.pythonmonkey.io/

Installation

Installing PythonMonkey is easy, you’ll just need to have npm and python installed on your system. Then install PythonMonkey using pip

$ pip install pythonmonkey

Example #1: Calling JavaScript Functions from Python

We’ll use the eval() function from PythonMonkey to evaluate JavaScript code in this example. It runs JavaScript code in a context and makes the functions, variables, etc available through pythonmonkey.gloablThis

import pythonmonkey as pm

# a string containing some javascript functions
my_js_code = """
function adder(a,b) {
  return a + b;
}

function subtracter(a,b) {
  return a - b;
}
"""

# put your javascript string inside pm.eval to execute it
pm.eval(my_js_code)

# call the adder function from Python
print(pm.globalThis.adder(1,2)) # outputs 3
print(pm.globalThis.adder(99,1)) # outputs 100

# call the subtracter function from Python
print(pm.globalThis.subtracter(1,2)) # outputs -1
print(pm.globalThis.subtracter(99,1)) # outputs 98

Example #2: Calling JavaScript Functions in another File from Python

In this example, we’ll use the require() function from PythonMonkey to load a JavaScript module into Python and call functions from it. This is just like how you would load a module in Node.js, but it works in Python!


In this example, we’ll use two files simple-math.js and main.py. The main.py Python script will call the JavaScript functions in simple-math.js.


main.py:

from pythonmonkey import require as js_require

js_lib = js_require('./simple-math')

print(js_lib.add(1,2)) #  3
print(js_lib.sub(1,2)) # -1


simple-math.js

function add(a,b) {
  return a + b;
}

function sub(a,b) {
  return a - b;
}

// We'll define the exports object just like in Node.js / npm modules
module.exports = {
  add,
  sub,
}


Then, if we execute main.py by typing $ python3 main.py we’ll get our results:

3

-1


I hope you found this article useful, here are some additional PythonMonkey resources you may find helpful:



Consider giving PythonMonkey a star on GitHub to support it! (https://github.com/Distributive-Network/PythonMonkey)!