DukPy
DukPy is a simple, lightweight JavaScript interpreter for Python, embedding the Duktape JavaScript engine. It allows executing JavaScript code directly from Python applications. As of version 0.5.1, it supports modern Python versions (up to 3.14) and maintains a steady release cadence, often aligning with new Python releases or Duktape engine updates.
Warnings
- breaking Support for older Python versions (2.x, 3.4-3.6) has been deprecated and eventually removed. Modern versions of DukPy require Python 3.7+.
- gotcha Versions prior to 0.4.0 might crash or produce incorrect output when handling JavaScript strings containing unicode emoji or other non-Basic Multilingual Plane (BMP) characters, due to encoding issues.
- gotcha Versions prior to 0.2.2 contained a memory leak in the `dukpy.evaljs` function, which could lead to increased memory consumption in long-running applications.
- gotcha When using `python_functions` to expose Python callables to JavaScript, ensure the function name matches exactly. Older versions (pre-0.3.1) might provide less informative error messages if the function is not found.
- gotcha If pre-built wheels are not available for your specific platform/Python version, `pip install dukpy` will attempt to build from source, which requires a C compiler (e.g., GCC or Clang) installed on your system.
Install
-
pip install dukpy
Imports
- evaljs
import dukpy; dukpy.evaljs(...)
Quickstart
import dukpy
# Basic JavaScript evaluation
result = dukpy.evaljs("1 + 2")
print(f"1 + 2 = {result}")
# Passing data to JavaScript
result = dukpy.evaljs("a + b", data={'a': 10, 'b': 20})
print(f"a + b (with data) = {result}")
# Calling Python functions from JavaScript
def my_python_sum(x, y):
return x + y
js_code = "var sum = my_python_sum(5, 7); sum;"
result = dukpy.evaljs(js_code, python_functions={'my_python_sum': my_python_sum})
print(f"JS calling Python function = {result}")