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
BioThings API framework - Making high-performance API for biological annotation data

BioThings SDK Quick Summary BioThings SDK provides a Python-based toolkit to build high-performance data APIs (or web services) from a single data sou

BioThings 39 Jan 04, 2023
I-Spy is a discord and twitter bot 🤖 that keeps a check on usage foul language, hate-speech and NSFW contents

I-Spy is a discord and twitter bot 🤖 that keeps a check on usage foul language, hate-speech and NSFW contents. It is the one stop solution to monitor your discord servers and twitter handles against

Tia Saxena 5 Nov 16, 2022
CyberTKR - CyberTK-API

CyberTKR - CyberTK-API

TKR 2 Apr 08, 2022
Tiktok-bot - A Simple Tiktok bot With Python

Install the requirements pip install selenium pip install pyfiglet==0.7.5 How ca

Muchlis Faroqi 5 Aug 23, 2022
A Powerful, Smart And Simple Userbot In Pyrogram.

Eagle-USERBOT 🇮🇳 A Powerful, Smart And Simple Userbot In Pyrogram. Support 🚑 Inspiration & Credits Userge-X Userge Pokurt Pyrogram Code Owners Mast

Masterolic 1 Nov 28, 2021
tgEasy's Official Assistant Bot and Example Bot

tgEasy Assistant The assistant bot that helps people with tgEasy directly on Telegram. This repository contains the source code of @tgEasyRobot and th

Divide Projects™ 4 Dec 26, 2022
A program that generates discord.py code

discord-py-generator A program that generates discord.py code Setup in cmds.txt file add your user id, client id and bot token you can change the bot

3 Dec 15, 2022
this synchronizes my appearances with my calendar

Josh's Schedule Synchronizer Here's the "problem:" I use a spreadsheet to maintain all my public appearances. I check the spreadsheet as often as poss

Josh Long 2 Oct 18, 2021
Catware - A powerful grabber with a built in bot control system

catware A powerful grabber with a built in bot control system PLEASE NOTE THAT I

4 Feb 04, 2022
A secure and customizable bot for controlling cross-server announcements and interactions within Discord

DiscordBot A secure and customizable bot for controlling cross-server announcements and interactions within Discord. Within the code of the bot, you c

Jacob Dorfmeister 1 Jan 22, 2022
Joshua McDonagh 1 Jan 24, 2022
聚合空间测绘搜索(Fofa,Zoomeye,Quake,Shodan,Censys,BinaryEdge)

#Search-Tools Search-Tools集合比较常见的网络空间探测引擎 Fofa,Zoomeye,Quake,Shodan,Censys,BinaryEdge 简单说明 ICO搜索目前只有Fofa,Shodan,Quake支持 代理设置是防止在API请求过于频繁,或者在实战中,好多红队打

311 Dec 16, 2022
:cloud: Python API for ThePirateBay.

Unofficial Python API for ThePirateBay. Build Status Test Coverage Version Downloads (30 days) Installation $ pip install ThePirateBay Note that ThePi

Karan Goel 334 Oct 21, 2022
Yes, it's true :yellow_heart: This repository has 326 stars.

Yes, it's true! Inspired by a similar repository from @RealPeha, but implemented using a webhook on AWS Lambda and API Gateway, so it's serverless! If

510 Dec 28, 2022
Telegram vc userbot

Telegram Vc Userbot Available Commands /ping :- To check whether userbot is up or not /joinvc :- To join vc /leavevc :- To leave vc /join_group :- To

NandyDark 7 Nov 18, 2022
A Telegram bot that can stream Telegram files to users over HTTP.

T.ME_FILE_TO_LINK Hi iam a file to link bot....best Bot telegram Telegram File To Link Generation Bot A Telegram bot that can stream Telegram files to

1 Oct 24, 2021
A little proxy tool based on Tencent Cloud Function Service.

SCFProxy 一个基于腾讯云函数服务的免费代理池。 安装 python3 -m venv .venv source .venv/bin/activate pip3 install -r requirements.txt 项目配置 函数配置 开通腾讯云函数服务 在 函数服务 新建 中使用自定义

Mio 716 Dec 26, 2022
A Telegram Bot To Stream Videos in Telegram Voice Chat.

Video Stream X Bot Telegram bot project for streaming video on telegram video chat, powered by tgcalls and pyrogram Deploy to Heroku 👨‍🔧 The easy wa

Mⷨoͦns͛ᴛⷮeͤrͬ Zeͤrͬoͦ 13 Dec 05, 2022
Techie Sneh 19 Dec 03, 2021
AWSXenos will list all the trust relationships in all the IAM roles and S3 buckets

AWS External Account Scanner Xenos, is Greek for stranger. AWSXenos will list all the trust relationships in all the IAM roles, and S3 buckets, in an

AirWalk 57 Nov 07, 2022