Search code examples
javascriptpythonhtmllibrariesbrython

Brython python to javascript converter


I want to create a tool using brython that translates python to js without running it. I know that there is a way to do it (i was doing some research: http://www.brython.info/tests/precompile.html or Python to JavaScript converter) but still i can't make it. The goal is to make html file like this below, but instead of copying and pasting same value to the second textarea actualy convert it to javascript?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <textarea name="input" id="input" cols="30" rows="10">Here write your python code...</textarea>
    <button id="convert" onclick="convert()">Convert</button>
    <textarea name="output" id="output" cols="30" rows="10">Here you will receive your javascript code...</textarea>

    <script>
        function convert(content)
        {
            var input = document.getElementById("input");
            var output = document.getElementById("output");
            
            output.innerHTML = input.innerHTML;
        }
    </script>

</body>
</html>

I tried to make python to js converter without frameworks such as Flask or Django, obviously it won't be a problem If you will suggest to use another js library for this like pyjs, javascrypthon or anything else.


Solution

  • Brython won't do what you intend there, if you are thinking in terms of "Google Translate": Brython can run transpiled Python in the javascript VM, but in doing so, it runs hundreds or thousands of lines of code embedded in the Brython javascript code itself.

    So, in order to run a "simple code" as:

    for i in range(10):
        print(i)
    

    It won't simply do a search and replace of this for a javascript for statement and a console.log. It will run this mimicking Python's internals up to a certain depth, at which point it executes Javascript primitives - that means it will have a range object with a __iter__ method - the for command will create a Python iterator for that, and call its __next__ method until a StopIteration exception is raised, then it catch it in a Python except statement and exit the loop. Even if Brython could select only the lines needed to run this subset of Python, that would amount to nearly 100 lines of code.