Js2Py: JavaScript to Python Translator & Interpreter
Js2Py is a pure Python library that acts as both a JavaScript to Python translator and a JavaScript interpreter. It allows Python developers to execute JavaScript code directly within their Python applications, or convert it to equivalent Python code. The current version is 0.74, and it sees active, though not strictly scheduled, development.
Warnings
- gotcha Js2Py is a pure Python implementation and is not designed for high-performance JavaScript execution. It will be significantly slower than engines like V8 (Node.js/Chromium) or SpiderMonkey.
- gotcha The interpreter primarily supports ECMAScript 5.1 and a limited set of ECMAScript 6 (ES2015) features. Newer JavaScript syntax (ES2016+, async/await, modern modules, etc.) may not be supported or lead to unexpected behavior.
- gotcha Type conversions between Python and JavaScript objects can be complex and sometimes lead to unexpected behavior. While basic types (numbers, strings, booleans, lists, dictionaries) are generally mapped, custom JS objects or complex Python objects may not translate as expected.
- gotcha As a pure Python library, Js2Py operates within the Python Global Interpreter Lock (GIL). Long-running JavaScript scripts will block the entire Python process, impacting concurrency for other Python threads.
- gotcha While Js2Py aims to provide a sandboxed environment for executing JavaScript, running arbitrary untrusted code always carries inherent security risks. A pure Python sandbox might have different vulnerabilities than a native V8 sandbox.
Install
-
pip install js2py
Imports
- eval_js
from js2py import eval_js
- translate_js
from js2py import translate_js
Quickstart
import js2py
# Define a JavaScript function
js_code = """
function greet(name) {
return 'Hello, ' + name + '!';
}
"""
# Evaluate the JavaScript code and get a Python callable object
js_greet = js2py.eval_js(js_code)
# Call the JavaScript function from Python
result_func = js_greet('World')
print(f"Function result: {result_func}")
# You can also evaluate a simple expression directly
direct_result = js2py.eval_js('10 * 5')
print(f"Direct expression result: {direct_result}")