Git Product home page Git Product logo

jspython-dev / jspython Goto Github PK

View Code? Open in Web Editor NEW
66.0 3.0 8.0 428 KB

JSPython is a python-like syntax interpreter implemented with javascript that runs entirely in the web browser and/or in the NodeJS environment.

Home Page: https://jspython.dev

License: BSD 3-Clause "New" or "Revised" License

HTML 2.04% JavaScript 11.21% TypeScript 86.75%
python-language interpreter python-interpreter javascript-evaluation

jspython's Introduction

JSPython

JSPython is a python-like syntax interpreter implemented with javascript that runs entirely in the web browser and/or in the NodeJS environment.

It does not transpile/compile your code into JavaScript, instead, it provides an interactive interpreter that reads Python code and carries out their instructions. With JSPython you should be able to safely use or interact with any JavaScript libraries or APIs in a nice Python language.

arr = [4, 9, 16]

def sqrt(a):
 return Math.sqrt(a)

# use Array.map() with Python function
roots = arr.map(sqrt).join(",")

# use Array.map() or use arrow function
roots = arr.map(i => Math.sqrt(i)).join(",")

Try out JSPython in the wild

Interactive Worksheet Systems JSPython editor with an ability to query REST APIs and display results in Object Explorer, a configurable Excel-like data grid or just as a JSON or text.

Why would you use it?

You can easily embed JSPython into your web app and your end users will benefit from a Python-like scripting facility to:

  • to build data transformation and data analysis tasks
  • allow users to configure JS objects at run-time
  • run a comprehensive testing scenarios
  • experiment with your JS Libraries or features.
  • bring a SAFE run-time script evaluation functions to your web app
  • bring Python language to NodeJS environment

Features

Our aim here is to provide a SAFE Python experience to Javascript or NodeJS users at run-time. So far, we implement a core set of Python feature which should be OK to start coding.

  • Syntax and code flow Same as Python, In JSPython we use indentation to indicate a block of code. All flow features like if - else, for, while loops - along with break and continue

  • Objects, Arrays JSPython allows you to work with JavaScript objects and arrays and you should be able to invoke their methods and properties as normal. So, all methods including prototype functions push(), pop(), splice() and many more will work out of box.

  • JSON JSPython allows you to work with JSON same way as you would in JavaScript or Python dictionaries

  • Functions Functions def def async def, arrow functions => - (including multiline arrow functions)

  • Strings Syntax and code flow s = "Strings are double quoated only! For now." represent a multiline string. A single or triple quotes are not supported yet.

  • Date and Time We have dateTime() function what returns JavaScript's Date object. So, you can use all Date get and set methods

  • None, null null and None are synonyms and can be used interchangeably

JSPython distinctive features

We haven't implemented all the features available in Python yet. However, we do already have several useful and distinctive features that are popular in other modern languages, but aren't in Python:

  • A single line arrow functions => (no lambda keyword required)
  • A multiline arrow function =>. Particularly useful when building data transformation pipelines
  • Null conditioning (null-coalescing) myObj?.property?.subProperty or "N/A".

Quick start

Zero install ! The simplest way to get started, without anything to install, is to use the distribution available online through jsDelivr. You can choose the latest stable release :

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/jspython-interpreter/dist/jspython-interpreter.min.js">
</script>

Or local install

npm install jspython-interpreter

Run JS Python from your Javascript App or web page.

Basic

  jsPython()
    .evaluate('print("Hello World!")')
    .then(
        r => console.log("Result => ", r),
        e => console.log("Error => ", error)
    )

Or with your own data context and custom function:

  const script = `
  x = [1, 2, 3]
  x.map(r => add(r, y)).join(",")
  `;
  const context = {y: 10}

  const result = await jsPython()
    .addFunction("add", (a, b) => a + b)
    .evaluate(script, context);
  // result will be a string "11,12,13"

Also, you can provide an entire JS Object or even a library.

Run JSPython in a NodeJS with JSPython-CLI

JSPython-cli is a command line tool what allows you to run JSPython in NodeJS environment

License

A permissive BSD 3-Clause License (c) FalconSoft Ltd.

jspython's People

Contributors

appleplectic avatar ppaska avatar tscharich avatar viktorkukurba avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

jspython's Issues

Tests fail when run from Paris timezone.

Test
expect(o[2][1].toISOString()).toBe(new Date('2020-03-07').toISOString());

fails in the French timezone.

> new Date('2020-03-07').toISOString()
'2020-03-07T00:00:00.000Z'
> o[2][1].toISOString()
'2020-03-06T23:00:00.000Z'

For info:

> new Date('2020-03-07T00:00:00').toISOString()
'2020-03-06T23:00:00.000Z'

Passing value type functions to the arrow function

This code doesn't work

x = [1, 2,3,4,5,6]
sum = 0
f.forEach(v => sum = sum + v)
print(sum) # incorrect sum will be here

# workaround is to add it to the object. e.g.

sum = {value: 0}
f.forEach(v => sum.value = sum.value + v)
print(sum.value) # correct sum will be here

Error does not evaluate parameters

Doesn't work

msg = 'Some error message'
raise Error(msg)

Works

# only string constant can be passed to Error
raise Error('Some error message')

Undefined node elif

I'm trying to parse a python code into an AST but every time I add an elif statement, it gives me the following error:
image
Thanks for the help!

quotes parsing error

the following gets interpreted successfully, although the syntax is wrong!

const {jsPython} = require("jspython-interpreter");

const script = `
    'hello world
`

jsPython()
  .evaluate(script)
  .then((result) => {
    console.log(result);
  })
  .catch((error) => {
    console.log(error);
  });

Prioritizing operations

At the moment we are not taking into account neither logical priorities nor brackets

# this should return 14 and not 24
2 + 3 * 4  

# this should return 20
(2 + 3) * 4

jsPython isn't defined

I am trying to use this library for parsing python and then displaying the result on web page client side.

I am importing it via cdn inside head described in docs

and then running this code in my script at the end of body

jsPython() .evaluate('print("Hello World!")') .then( r => console.log("Result => ", r), e => console.log("Error => ", error) )

It says jsPython is undefined

Error codes

Hi
When there is an error in a user's "python" program, is there a way to capture does errors?
Maybe by error codes?
I want to return to the user a custom error message
Thank you

Dynamic JSON keys

{
   "Year-" + dateTime().getFullYear(): "some value"
}

The code above doesn't work! The workaround.

obj = {}
obj["Year-" + dateTime().getFullYear()] = "some value"

Error "Tokens length can't empty"

Trying code:

today = dateTime() # now
print (today.valueOf())

get error:
JspyParserError: main.jspy(2,8): Tokens length can't empty.

Why? valueOf exists in today

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.