从Javascript代码调用Python函数

我想从Javascript代码中调用Python函数,因为在Javascript没有替代方法来执行我想要的操作。 这可能吗? 你可以调整下面的代码片段?

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 

包含使用高级库的函数,在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) 

所有你需要的是向你的pythoncode发出一个ajax请求。 你可以用jquery http://api.jquery.com/jQuery.ajax/来做到这一点,或者使用javascript

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

document.getElementsByTagName我猜你正在浏览器中运行JavaScript。

向浏览器中运行的JavaScript公开function的传统方式是使用AJAX调用远程URL。 AJAX中的X用于XML,但是现在大家都使用JSON而不是XML。

例如,使用jQuery,你可以做如下的事情:

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

你将需要在服务器端实现一个python webservice。 对于简单的Web服务,我喜欢使用Flask 。

典型的实现如下所示:

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

你可以在Silverlight的浏览器中运行IronPython(一种Python.Net),但我不知道NLPK是否可用于IronPython。

通常,您可以使用类似于下面的ajax请求来完成此操作。

 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(); 

你不能运行没有python.exe的JavaScript的.py文件,就像你不能运行没有notepad.exe的.txt文件一样。 但是整个事情在Web API服务器(下面的例子中的IIS)的帮助下变得喘不过气来。

  1. 安装python并创build一个示例文件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. 在您的Web API服务器中创build一个方法

     [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. 现在为您的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); } }); }