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.
pip install js2pyVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to evaluate a JavaScript code string and interact with defined functions, as well as directly evaluate simple expressions. `eval_js` returns a `PyJs` object or a Python equivalent of the JS return value.
Consider alternative solutions like `py_mini_racer` (V8 bindings) for performance-critical tasks, or Node.js subprocess calls.
Ensure your JavaScript code adheres to ES5.1 compatibility or thoroughly test for ES6 features you intend to use. Consult the project's GitHub for current compatibility details.
Familiarize yourself with the 'Python and JavaScript object mapping' section in the Js2Py documentation. Test conversions thoroughly for critical data structures and object interactions.
For long-running or CPU-bound JavaScript tasks, consider offloading them to separate processes using Python's `multiprocessing` module, or use asynchronous execution patterns if the JS itself is non-blocking.
Never execute JavaScript from untrusted sources without careful consideration and robust input validation. Even with sandboxing, exercise caution and minimize the attack surface if Js2Py is used in security-sensitive contexts.