I have a Python script and a JS on my server. In the python script, I want to set the value of a variable to be the output of one of the functions in my .js file.
Is this possible, and if so how wold one go about doing this?
Thanks!
I have a Python script and a JS on my server. In the python script, I want to set the value of a variable to be the output of one of the functions in my .js file.
Is this possible, and if so how wold one go about doing this?
Thanks!
It is not possible, as Javascript usually runs on the client side, while Python runs on the server side.
If it is code that needs to run on the client side, have it send an AJAX request to a python script with the results you need. If it does not need to run on the client side, I suggest you rewrite it in Python.
As an alternative to what Macha proposes (an Ajax query) you could also create the Javascript file dynamically.
When the page is loaded, the javascript is loaded. In your page is the URL to the javascript in the form of
<SCRIPT LANGUAGE="JAVASCRIPT" SRC="mycode.js" TYPE="TEXT/JAVASCRIPT">
The trick is now to let the server not serve a static file "mycode.js" but the output of e.g. mycode.py. Your tag would thus look like
<SCRIPT LANGUAGE="JAVASCRIPT" SRC="mycode.py" TYPE="TEXT/JAVASCRIPT">
and the python script would look possibly like (simplified):
var_value = "whatever you want the variable to be"
jsfile = open("myscript.js", "rb")
for line in jsfile:
print line.replace("$MYVAR$", var_value)
jsfile.close()
In short, you have your current js file, but you'd use it as a template for the python script. You substitute your variable with its value using replace.
It may not be the most elegant solution but it should work, and isn't all that difficult to understand.
Don't forget that your server should know how to handle python scripts :)
You can simply print javascript blocks from your python script... and set variables in those blocks that are used from the external script.
<script language="javascript">var myvalue="data";</script>
using simplejson you can even print arrays and stuff like that.
Just make sure that the code in your javascript file is in a function that is called after the whole page is loaded or load the javascript file at the end of the page.