usar una llamar funcion enlazar desde conectar con como javascript python function integration

javascript - una - python web html



Llamar a la función Python desde código Javascript (4)

Me gustaría llamar a una función de Python desde código Javascript , porque no hay una alternativa en Javascript para hacer lo que quiero. es posible? ¿Podría ajustar el siguiente fragmento para que funcione?

Parte de Javascript:

var tag = document.getElementsByTagName("p")[0]; text = tag.innerHTML; // Here I would like to call the Python interpreter with Python function arrOfStrings = openSomehowPythonInterpreter("~/pythoncode.py", "processParagraph(text)"); ~/pythoncode.py

contiene funciones que usan bibliotecas avanzadas que no tienen un equivalente fácil de escribir en Javascript

import nltk # is not in Javascript def processParagraph(text): ... nltk calls ... return lst # returns a list of strings (will be converted to `Javascript` array)


Desde document.getElementsByTagName supongo que está ejecutando el javascript en un navegador.

La forma tradicional de exponer la funcionalidad a javascript que se ejecuta en el navegador es llamar a una URL remota usando AJAX. La X en AJAX es para XML, pero hoy en día todo el mundo usa JSON en lugar de XML.

Por ejemplo, usando jQuery puedes hacer algo como:

$.getJSON(''http://example.com/your/webservice?param1=x&param2=y'', function(data, textStatus, jqXHR) { alert(data); } )

Tendrá que implementar un servicio web python en el lado del servidor. Para servicios web sencillos, me gusta usar Flask .

Una implementación típica se ve así:

@app.route("/your/webservice") def my_webservice(): return jsonify(result=some_function(**request.args))

Puede ejecutar IronPython (tipo de Python.Net) en el navegador con silverlight , pero no sé si NLTK está disponible para IronPython.


No puede ejecutar archivos .py desde JavaScript sin el programa Python, como no puede abrir archivos .txt sin un editor de texto. Pero todo se convierte en un aliento con la ayuda de un servidor de API web (IIS en el ejemplo a continuación).

  1. Instala Python y crea un archivo de muestra test.py

    import sys # print sys.argv[0] prints test.py # print sys.argv[1] prints your_var_1 def hello(): print "Hi" + " " + sys.argv[1] if __name__ == "__main__": hello()

  2. Crea un método en tu servidor de API web

    [HttpGet] public string SayHi(string id) { string fileName = HostingEnvironment.MapPath("~/Pyphon") + "//" + "test.py"; Process p = new Process(); p.StartInfo = new ProcessStartInfo(@"C:/Python27/python.exe", fileName + " " + id) { RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; p.Start(); return p.StandardOutput.ReadToEnd(); }

  3. Y ahora para su JavaScript:

    function processSayingHi() { var your_param = ''abc''; $.ajax({ url: ''/api/your_controller_name/SayHi/'' + your_param, type: ''GET'', success: function (response) { console.log(response); }, error: function (error) { console.log(error); } }); }

Recuerde que su archivo .py no se ejecutará en la computadora de su usuario, sino en el servidor.


Normalmente, lograrías esto usando una solicitud de Ajax que se parece a

var xhr = new XMLHttpRequest(); xhr.open("GET", "pythoncode.py?text=" + text, true); xhr.responseType = "JSON"; xhr.onload = function(e) { var arrOfStrings = JSON.parse(xhr.response); } xhr.send();


Todo lo que necesita es hacer una solicitud de Ajax a su pythoncode. Puede hacer esto con jquery http://api.jquery.com/jQuery.ajax/ , o use solo javascript

$.ajax({ type: "POST", url: "~/pythoncode.py", data: { param: text} }).done(function( o ) { // do something });