Run <py-script> manually

Hello, love the project. I’m trying to write my own simple REPL. I’d like to use the PyScript functionality to compile code, without the frontend boilerplate of py-repl. How can I take user input and run it manually? Here’s the gist of the code I have so far:

    <div id="py-container">
    </div>
    <div class="row col-12">
        <textarea id="python-editor"></textarea>
        <button id="run-button" class="btn btn-primary">Run</button>
    </div>
    <div id='output-container' class="row">
        <div id="out"></div>
    </div>

    <script>
        $('#run-button').click(function() {
            let code =$('#python-editor').val();
            let code_final = '<py-script id="input" output="out" output-mode="append"> ' + code + ' </py-script>'

            $('#py-container').append(code_final);
        });
    </script>

I’m using codemirror on my end, so I simplified the code a bit, but I did confirm that code_final returns
<py-script id="input" output="out" output-mode="append"> print('x') </py-script>. If I put this line directly in my code, it compiles on page load and “x” appears in the output div.

2 Likes

hi,

take a look at this

see

submit.addEventListener(“click”, pyodide.create_proxy(download_handler))

that is one way to add in events and call functions from clicks

is that the kinda thing you are looking for?

Great initiative by Anaconda! I have been looking for something like this for way too long!

Could you please provide a complete minimum example? Perhaps modifying the example WuTangClan provided, please?

For example, if we get the the user input code from the textarea as a string containing import statements etc., what would be the recommended way to execute that string?

i can make an example.

here, if you have the name of the import you want (say “'snowballstemmer”) in python in a var you can import with something like

import micropip
await micropip.install(‘snowballstemmer’)

or import a whl with something like

import micropip
await micropip.install(‘https://example.com/files/snowballstemmer-2.0.0-py2.py3-none-any.whl’)

1 Like

I might be missing your question, but maybe this example from Pyodide is what you’re looking for?

It wouldn’t really require a py-script tag though

@WuTangClan I have the same question as you. Did you figure it out?