Execute Javascript code in Python

Posted by Bruce Liu on February 15, 2023

🏷️ Tags: Python , Javascript

Python packages

Js2Py

PyExecJS - unmaintained.

Ways to implement

Firstly, install Js2Py then import js2py module:

import js2py

js code in place

js_code = '''
function add(a, b) {
  return a + b;
}
'''
add = js2py.eval_js(js_code)
add(1,2) + 3

js code in a file

Create a js file nameed with add.js:

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

Then,

with open('add.js') as f:
	add = js2py.eval_js(f.read())
add(1,2) + 3

online js code

There is a public link for the add function

https://raw.githubusercontent.com/longavailable/datarepo02/main/code/javascript/add.js

and,

import requests
js_link = 'https://raw.githubusercontent.com/longavailable/datarepo02/main/code/javascript/add.js'
add = js2py.eval_js(requests.get(js_link).text)
add(1,2) + 3
Python tools

Share on:

« PREVIOUS: Academic journals on water and environment
NEXT: Ports of free hydrodynamic models/softwares »