Search code examples
javascriptpythonparsingmultiple-languages

Retrieve Python variable in JavaScript


Is there some way I can retrieve a variable that was created using a Python script and use it in a JavaScript script?

For example, I parse an XML using Python to give me an int:

parse code parse code parse code
i = 3

Then in my JavaScript, I can use that variable "i" for some function:

code for my function
r = 30 / i 

Then the r value is equal to 10


Solution

  • Not directly as they are separate processes usually on separate computers that do not share memory or state. You didn't give much context in your question, so I am going to assume you are running python in a webserver and outputting HTML with JS either in the html or linked as an external source.

    If this is the case you have two options.

    1. Dynamically generate your JS and include it in the output of the python script (HTML response)

    One way of doing this is to load the Javascript in your python script via the open() function. Then prepend a string to this that is valid javascript code and define a variable or JSON object.

    Let's say you have this javascript file:

    javascript.js

    alert(my_js_data["field1"]);
    alert(my_js_data["field2"]);
    

    Here is your python script:

    import json
    
    # define your data you want in your javascript variable
    my_data = {'field1': 'string value', 'field2': 100}
    
    # open an existing script that is ready to use the my_js_data variable
    # we are about to generate
    js = open('javascript.js', 'r')
    
    # dynamically generate javascript code
    javascript_out = "var my_js_data = JSON.parse('{}');".format(json.dumps(my_data))
    javascript_out += js.read()
    

    Now, your javascript_out variable in python is a string that looks like this:

    var my_js_data = JSON.parse('{"field1": "string value", "field2": 100}');
    
    alert(my_js_data["field1"]);
    alert(my_js_data["field2"]);
    

    Without having more context, I can't tell you exactly what to do with the javascript_out variable, but you need to include it at the appropriate spot in your HTML.

    Note that the javascript.js file will not work without the python script because the my_js_data variable will not be defined.

    1. Have your Javascript make another HTTP (ajax) request to your server which will then return a JSON string with your data.