Giter Club home page Giter Club logo

jsengine's Introduction

JSEngine

This is a simple wrapper of Javascript engines, it wraps the Javascript interpreter for Python use.

There are two ways to call interpreters, via dynamic library loading is internal call which is faster than the other one, via subprocess is external call.

  • System's built-in Javascript interpreter:

    macOS: JavascriptCore
    Linux: Gjs on Gnome, CJS on Cinnamon, etc.
    Windows: Chakra (internal call, but not applicable to Windows 7)

  • Python bindings (Recommend, internal call):

    QuickJS
    PyChakra
    PyMiniRacer (V8) (Caused by a scope issue, its work process is similar to external call now, to fix the scope issue, Esprima is needed)

  • Any installed external Javascript interpreters, e.g.

    SpiderMonkey, Node.js, QuickJS, etc.

JSEngine used to be part of YKDL, which created by @coslyk.

Installation

Install from version package format monthly downloads

pip install jsengine

Or download and Install from source code

python setup.py install

Compatibility

  • Python >= 2.7

Usage

import jsengine
jsengine.eval('"Hello, world!"')  # => 'Hello, world!'

Use a JSEngine context.

try:
    ctx1 = jsengine.jsengine()
except jsengine.RuntimeError:
    ...  # do something if useless

if jsengine.JSEngine is None:
    ...  # do something if useless
else:
    ctx2 = jsengine.JSEngine("""
            function add(x, y) {
                return x + y;
            }
            """)

ctx1.eval('1 + 1')  # => 2

# call funtion
ctx2.call("add", 1, 2)  # => 3

# append new script
ctx1.append("""
    function square(x) {
        return x ** 2;
    }
    """)
ctx1.call("square", 9)  # => 81

Use a specified external Javascript interpreter.

binary = binary_name or binary_path
kwargs = {
    'name': 'None or any string',  # see ExternalInterpreterNameAlias.keys()
    'tempfile': True,              # use tempfile or not. Default is False, fallback is True
    'evalstring': True,            # can run command string as Javascript or can not,
                                   # just like '-e script_code'
                                   # instead of True, supported argument can be passed,
                                   # e.g. '--eval', '--execute'
    'args': [args1, args2, ...]    # arguments used for interpreter
}

# case 1
interpreter = jsengine.ExternalInterpreter.get(binary, **kwargs)
if interpreter:
    # found
    ctx = jsengine.ExternalJSEngine(interpreter)

# case 2
if jsengine.set_external_interpreter(binary, **kwargs):
    # set default external interpreter OK
    ctx = jsengine.ExternalJSEngine()

# case 3, maybe get default fallback instead of your specified
try:
    ctx = jsengine.ExternalJSEngine(interpreter=binary, **kwargs)
except jsengine.RuntimeError:
    ...  # do something if useless

Use threading lock. Javascript source itself always be ran in single threaded, that just make the APIs can be used in multithreadeding.

jsengine.set_threading(True)   # MUST enable befor using, it's disabled by default

ctx_quickjs = jsengine.QuickJSEngine()
ctx_chakra = jsengine.ChakraJSEngine()   # internal chakra will create an extra thread per context
ctx_v8 = jsengine.V8JSEngine()
ctx_exter = jsengine.ExternalJSEngine()  # external interpreter will be called one by one with context

...  # do multithreading

jsengine.set_threading(False)  # disable is not necessary

Internal VS. External

QuickJSEngine ChakraJSEngine V8JSEngine (esprima) V8JSEngine ** ExternalJSEngine
Load backend on import import or init init init every fetch result
Loading speed fastest fast very slow with py3 fast very slow
Performance highest high low, if much results low, if much results
Fetch result run the passed run the passed run the passed run all/full source run all/full source

* Fetch results means call eval()/call().
** V8JSEngine is now similar to ExternalJSEngine which caused by scope issue.

License

JSEngine is released under the MIT License.

jsengine's People

Contributors

seahoh avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

zackmark29

jsengine's Issues

How to work with bytearray?

Hello, could you please help me with bytearrays?

byte_array = bytearray.fromhex("93 14 2C 08")
array = ctx1.call("calculateKey", byte_array)

but i got

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x93 in position 0: invalid start byte

Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.