Python Wrapper for Google V8 Engine
STPyV8 is a Python wrapper for the Google V8 JavaScript engine, enabling seamless interoperability between Python 3 and JavaScript. It serves as a modern fork of the original PyV8 project, continuously updated by Cloudflare to align with the latest Google V8 engine branches and Python 3 versions. The library receives frequent updates, often coinciding with new V8 releases, and provides pre-built wheels for various platforms.
Warnings
- breaking STPyV8 requires Python 3.9 or newer for recent versions. Attempting to install or use with older Python versions may lead to build failures or runtime errors.
- gotcha When building STPyV8 from source (e.g., if no pre-built wheel is available for your platform/Python version), you will need a C++ compiler (GCC/clang on Linux/macOS, MSVC on Windows), Python development headers, and potentially Boost libraries (though less common for recent versions).
- gotcha For complex JavaScript code, the underlying V8 engine may require an ICU data file (`icudtl.dat`). If this file is not correctly packaged with your STPyV8 installation (e.g., when building from source or with certain distribution methods), V8 operations can fail silently or with errors.
- gotcha STPyV8's direct `eval()` might not fully support modern JavaScript ES Modules (`import`/`export` syntax) out-of-the-box, potentially leading to `SyntaxError: Cannot use import statement outside a module`.
- gotcha There are reported issues with STPyV8 in multi-threaded environments, including segmentation faults when used in separate threads. The presence of dual garbage collectors (Python and V8) can also lead to complexities and potential memory management issues in scenarios involving long-lived objects spanning both VMs.
Install
-
pip install stpyv8
Imports
- STPyV8
import STPyV8
- JSContext
from STPyV8 import JSContext
- JSClass
from STPyV8 import JSClass
Quickstart
import STPyV8
with STPyV8.JSContext() as ctxt:
result = ctxt.eval("'Hello, ' + 'STPyV8!'");
print(result)
# Exporting a Python function to JavaScript
class MyFunctions(STPyV8.JSClass):
def multiply(self, a, b):
return a * b
my_funcs = MyFunctions()
with STPyV8.JSContext(my_funcs) as ctxt:
js_code = "this.multiply(5, 3);"
multiplication_result = ctxt.eval(js_code)
print(f"Multiplication result: {multiplication_result}")