Embed the Duktape JS interpreter in Python

Overview

Introduction

Pyduktape is a python wrapper around Duktape, an embeddable Javascript interpreter.

On top of the interpreter wrapper, pyduktape offers easy integration between the Python and the Javascript environments. You can pass Python objects to Javascript, call methods on them and access their attributes. Similarly, you can pass Javascript objects to Python.

Objects are never copied or serialized. Instead, they are passed between the two environments using proxy objects. Proxy objects delegate the execution to the original object environment.

Threading

It is possible to invoke Javascript code from multiple threads. Each thread will need to use its own embedded interpreter. Javascript objects returned to the Python environment will only be usable on the same thread that created them. The runtime always checks this condition automatically, and raises a DuktapeThreadError if it's violated.

Getting Started

Installation

To install from pypi:

$ pip install -U setuptools
$ pip install pyduktape

To install the latest version from github:

$ git clone https://github.com/stefano/pyduktape.git
$ cd pyduktape
$ pip install -U setuptools
$ python setup.py install

Running Javascript code

To run Javascript code, you need to create an execution context and use the method eval_js:

import pyduktape

context = pyduktape.DuktapeContext()
context.eval_js("print('Hello, world!');")

Each execution context starts its own interpreter. Each context is independent, and tied to the Python thread that created it. Memory is automatically managed.

To evaluate external Javascript files, use eval_js_file:

// helloWorld.js
print('Hello, World!');

# in the Python interpreter
import pyduktape

context = pyduktape.DuktapeContext()
context.eval_js_file('helloWorld.js')

Pyduktape supports Javascript modules:

// js/helloWorld.js
exports.sayHello = function () {
    print('Hello, World!');
};

// js/main.js
var helloWorld = require('js/helloWorld');
helloWorld.sayHello();

# in the Python interpreter
import pyduktape

context = pyduktape.DuktapeContext()
context.eval_js_file('js/main')

The .js extension is automatically added if missing. Relative paths are relative to the current working directory, but you can change the base path using set_base_path:

# js/helloWorld.js
print('Hello, World!');

# in the Python interpreter
import pyduktape

context = pyduktape.DuktapeContext()
context.set_base_path('js')
context.eval_js_file('helloWorld')

Python and Javascript integration

You can use set_globals to set Javascript global variables:

import pyduktape

def say_hello(to):
    print 'Hello, {}!'.format(to)

context = pyduktape.DuktapeContext()
context.set_globals(sayHello=say_hello, world='World')
context.eval_js("sayHello(world);")

You can use get_global to access Javascript global variables:

import pyduktape

context = pyduktape.DuktapeContext()
context.eval_js("var helloWorld = 'Hello, World!';")
print context.get_global('helloWorld')

eval_js returns the value of the last expression:

import pyduktape

context = pyduktape.DuktapeContext()
hello_world = context.eval_js("var helloWorld = 'Hello, World!'; helloWorld")
print hello_world

You can seamlessly use Python objects and functions within Javascript code. There are some limitations, though: any Python callable can only be used as a function, and other attributes cannot be accessed. Primitive types (int, float, string, None) are converted to equivalent Javascript primitives. The following code shows how to interact with a Python object from Javascript:

import pyduktape

class Hello(object):
    def __init__(self, what):
        self.what = what

    def say(self):
        print 'Hello, {}!'.format(self.what)

context = pyduktape.DuktapeContext()
context.set_globals(Hello=Hello)
context.eval_js("var helloWorld = Hello('World'); helloWorld.say();")

In the same way, you can use Javascript objects in Python. You can use the special method new to instantiate an object:

import pyduktape

context = pyduktape.DuktapeContext()
Hello = context.eval_js("""
function Hello(what) {
    this.what = what;
}

Hello.prototype.say = function () {
    print('Hello, ' + this.what + '!');
};

Hello
""")

hello_world = Hello.new('World')
hello_world.say()

You can use Python lists and dicts from Javascript, and viceversa:

import pyduktape

context = pyduktape.DuktapeContext()
res = context.eval_js('[1, 2, 3]')

for item in res:
    print item

context.set_globals(lst=[4, 5, 6])
context.eval_js('for (var i = 0; i < lst.length; i++) { print(lst[i]); }')

res = context.eval_js('var x = {a: 1, b: 2}; x')
for key, val in res.items():
    print key, '=', val
res.c = 3
context.eval_js('print(x.c);')

context.set_globals(x=dict(a=1, b=2))
context.eval_js("""
var items = x.items();
for (var i = 0; i < items.length; i++) {
    print(items[i][0] + ' = ' + items[i][1]);
}
""")
context.set_globals(x=dict(a=1, b=2))
context.eval_js('for (var k in x) { print(k + ' = ' + x[k]); }')
Owner
Stefano
Stefano
Automatically mass follows tons of NameMC profiles.

Automatically mass follows tons of NameMC profiles. (Creates REAL traffic to your profile)

Jam 3 Jun 29, 2022
Twitter FakeNFT With Python

This project is a server that fetches your Twitter profile picture and applies the hexagonal transparency mask displayed on the profiles of users who have an NFT profile picture.

Mathis HAMMEL 29 Apr 23, 2022
Update your World of Warcraft AddOns hosted on GitHub

AddOns Update Tool Tool to update World of Warcraft AddOns hosted on GitHub Features Pure Python: only Dulwich and Colorlog Multithreaded tasks Manual

Mr. Alchemist 16 Dec 06, 2022
Get some python in google cloud functions

[NOTE]: This is a highly experimental (and proof of concept) library so do not expect all python packages to work flawlessly. Also, cloud functions ar

Martin Abelson Sahlen 200 Nov 24, 2022
gBasic - The easy multiplatform bot

gBasic The easy multiplatform bot gBasic is the module at the core of @GianpiertoldaBot, maintained with 3 for the entire community by the Stockdroid

Stockdroid Fans 5 Nov 03, 2021
Bearer API client for Python

Bearer Python Bearer Python client Installation pip install bearer Usage Get your Bearer Secret Key and integration id from the Dashboard and use the

Bearer 9 Oct 31, 2022
Box SDK for Python

Box Python SDK Installing Getting Started Authorization Server-to-Server Auth with JWT Traditional 3-legged OAuth2 Other Auth Options Usage Documentat

Box 371 Dec 29, 2022
Renjith Mangal 10 Oct 28, 2022
Kyura-Userbot: a modular Telegram userbot that runs in Python3 with a sqlalchemy database

Kyura-Userbot Telegram Kyura-Userbot adalah userbot Telegram modular yang berjal

Kyura 17 Oct 29, 2022
Easy & powerful bot to check if your all Telegram bots are working or not

Easy & powerful bot to check if your all Telegram bots are working or not. This bot status bot updates every 105 minutes & runs for 24x7 hours.

35 Dec 30, 2022
AWS Workmail Migration Tool

WMigrate A tool for migrating AWS Workmail Users and Groups cross region and cross accounts. It also creates user and group aliases and adds the users

NK 1 Oct 27, 2021
Td-Ameritrade, Tradingview, Webhook, AWS Chalice

TDA-Autobot TDA-Autobot is an automated fire and forget trading mechanism utilizing Alex Golec's(Author) tda-api wrapper, Tradingview webhook alerts,

Kyle Jorgensen 2 Dec 12, 2021
MashaRobot : New Generation Telegram Group Manager Bot (🔸Fast 🔸Python🔸Pyrogram 🔸Telethon 🔸Mongo db )

MashaRobot Me On Telegram ✨ MASHA ✨ This is just a demo bot.. Don't try to add to your group.. Create your own bot How To Host The easiest way to depl

Mr Dark Prince 40 Oct 09, 2022
A simple Telegram bot that can add caption to any media on your channel

Channel Auto Caption This bot can add a caption for any media/document sent to a channel. Just deploy bot and add bot as admin to a channel. Deploy to

22 Nov 14, 2022
A Discord bot to play bluffing games like Dobbins or Bobbins

Usage: pip install -r requirements.txt python3 bot.py DISCORD_BOT_TOKEN Gameplay: All commands are case-insensitive, with trailing punctuation and spa

4 May 27, 2022
A powerfull Telegram Leech Bot

owner of this repo :- Abijthkutty contact me :- Abijth Telegram Torrent and Direct links Leecher Dont Abuse The Repo ... this is intented to run in Sm

αвιנтн 9 Jun 11, 2022
Biblioteca Python que extrai dados de mercado do Bacen (Séries Temporais)

Pybacen This library was developed for economic analysis in the Brazilian scenario (Investments, micro and macroeconomic indicators) Installation Inst

42 Jan 05, 2023
Tools to help record data from Qiskit jobs

archiver4qiskit Tools to help record data from Qiskit jobs. Install with pip install git+https://github.com/NCCR-SPIN/archiver4qiskit.git Import the

0 Dec 10, 2021
A Telegram Bot with(Forwarder Bot + User Bot + More Features )

A Telegram Bot with(Forwarder Bot + User Bot + More Features )

Kaif 3 Feb 16, 2022
Monetize your apps with KivAds using Google AdMob api.

KivAds(WIP) Monetize your apps with KivAds using Google AdMob api. KivAds uses the latest version of Google AdMob sdk(version 20.0.0). KivAds exposes

Guhan Sensam 16 Nov 05, 2022