1

I'm writing a simple web/e-book that demonstrates concepts using some Python code in between the texts. I was wondering what could be a simple way for me to add a javascript/Vue/React widget that can evaluate the Python code that it contains and spit out the output below it.

All the options that I've looked so far are Python 'for web' solutions (Brython, etc.) but I don't think that that's what I need in my case. The solution that comes to my mind is to transpile the Python code snippets on the webpage in JavaScript and then evaluate it and print the output.

6
  • 1
    Why not Brython? Commented Jul 25, 2020 at 19:47
  • This is gonna be pretty hard if you want a language complete solution. Typically you would send the code off to a server, execute it there, then send the results back. If you knew that there were only going to be few simple commands/keywords used, then sure you can build yourself a basic transpiler, but anything more than that and you're gonna need to go bigger. The problem will just "including python in the page" is that Python is so large its not feasible to just transmit it across the internet, and so different that its a big task to just "convert to javascript". :D Commented Jul 25, 2020 at 19:48
  • @dantechguy that was my fear too. @szatkus I can't figure out Brython usage at all! Can't even run print('hello world!'). Commented Jul 25, 2020 at 19:51
  • @DaveIdito From my quick google, Brython tries to entirely replace javascript in your website, so you can write your whole page without a single bit of JS to be seen, rather than provide a small snippet of Python. It might be worth trying nonetheless Commented Jul 25, 2020 at 19:52
  • It would be extremely helpful if you provided the Brython code you tried. Commented Jul 25, 2020 at 19:55

4 Answers 4

2

Longer response.

I played a bit on Brython demo site, and it really seems to fit your problem.

There is a global object __BRYTHON__ which seems to include everything what you need to run Python code in a browser. The simple hello world looks like that:

__BRYTHON__.run_py('print("Hello world!")', 'file.py', {__name__: 'asd'})

The default output is console.log, but I found an object __BRYTHON__.stdout which you can replace with your own implementation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This may very well be the answer. I'll try and test it asap and update here.
Did not work for me. I created a ticket: github.com/brython-dev/brython/issues/2339
0

Not totally sure if this fits your use case, but another possibility is Binder, which is what I believe the spaCy library uses for their docs and allows you to run snippets in the browser.

Here's another example from spaCy.

Maybe not the answer if you're trying to avoid the "send the code off to a server option", but maybe someone else could find it useful, at the very least.

Comments

0

I realize this is an old question so it may not help too much with your webbook, but for future people coming across this question there are now a few ways to run Python in the browser.

Pyodide is a great packages which runs a Python interpreter inside of the browser using WebAssembly.

PyScript is a project built on top of Pyodide which allows running python using the <pyscript> tag. However, it is very slow to load and doesn't provide a great interfaces for editing and demo-ing Python.

This is where PyPrez comes in (Disclaimer: I am the author). PyPrez is built to allow you to easily embed runnable and editable codeblocks in the browser. It is tailor made for use cases such as interactive Python tutorials or webbooks like what you describe. In fact, it even works in StackOverflow answers if you click Run Code Snippet

# python example

class Car(object):
    num_wheels = 4
    mpg = 20
    gas_capacity = 15
    class NotEnoughGasError(Exception):
        pass
   
    def __init__(self):
        self.odometer = 0
        self.gas = self.gas_capacity

    def drive(self, miles):
        gallons_needed = miles / self.mpg
        if not self.gas > gallons_needed:
            raise self.NotEnoughGasError(f"{miles}mi trip requires {gallons_needed} gallons of gas but there are only {self.gas} gallons left")
        print(f"driving {miles} miles")
        self.odometer += miles
        self.gas -= gallons_needed

    def fill_gas(self):
        self.gas = self.gas_capacity

if __name__ == "__main__":
    my_car = Car()
    my_car.drive(200)
    my_car.drive(50)
    my_car.drive(75)
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>

Comments

0

Use Pyodide:

    <!doctype html>
    <html>
      <head>
          <script src="https://cdn.jsdelivr.net/pyodide/v0.24.1/full/pyodide.js"></script>
      </head>
      <body>
        Pyodide test page <br>
        Open your browser console to see Pyodide output
        <script type="text/javascript">
          async function main(){
            let pyodide = await loadPyodide();
            console.log(pyodide.runPython(`
                import sys
                sys.version
            `));
            pyodide.runPython("print(1 + 2)");
          }
          main();
        </script>
      </body>
    </html>

https://pyodide.org/en/stable/usage/quickstart.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.