1

I have a HTML input and onClick with a button, I get the value of text input and store in a varibale in Javascipt. Now how can I use this varibale as a paramter to a python function?

In JavaScript I have:

var text = document.getElementById("text").value;

and in Python I have:

someFunction(text):
   print(text) # text is what I want to be passed from javascript

I am using pyscript to run my python codes

4

2 Answers 2

1

You can submit the form to send values to a Python file or use API's with Ajax this article about difference between server-side and client-side.

And in regard to @JohnHanley comment you can use py-script to do that, take a look here

<link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
<script defer src="https://pyscript.net/latest/pyscript.js"></script>

<script>
    name = "Guido" //A JS variable

    // Define a JS Function
    function addTwoNumbers(x, y){
        return x + y;
    }
</script>

<py-script>
    # Import and use JS function and variable into Python
    from js import name, addTwoNumbers

    print(f"Hello {name}")
    print("Adding 1 and 2 in Javascript: " + str(addTwoNumbers(1, 2)))
</py-script>

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

4 Comments

PyScript/Python runs in the browser.
@JohnHanley You're right, I totally forgot about py-script that's my bad
@MohamedEL-Gendy As per OP, He want to get the updated text into the python script dynamically. But as per your demo it is print the static calculation based on param passed. Can you please make it as per the dynamic input passed from the text box ?
@RohìtJíndal Maybe you will need to use the event listener handler in PyScript. Check this tutorial how to add an Event Listener to your PyScript
0

You can do a GET or a POST from your page to the python script. AJAX makes this quite easy for you - there is an existing answer to a similar question here on stack, have a look at:

Passing Javascript variable to Python

You might find it easier to parcel up the variable in a little json, which makes the GET/POST nice and simple, then import json in your python code and modify the function accordingly.

Also probably need to define an endpoint so the server knows to execute the python script

1 Comment

PyScript/Python runs in the browser.

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.