从JavaScript代码调用Python函数
我想从JavaScript代码中调用Python函数,因为JavaScript中没有其他方法可以实现我想要的功能。这可能吗?你能调整一下下面的代码片段吗 JavaScript代码:从JavaScript代码调用Python函数,javascript,python,function,integration,Javascript,Python,Function,Integration,我想从JavaScript代码中调用Python函数,因为JavaScript中没有其他方法可以实现我想要的功能。这可能吗?你能调整一下下面的代码片段吗 JavaScript代码: var tag=document.getElementsByTagName(“p”)[0]; text=tag.innerHTML; //这里我想用Python函数调用Python解释器 arrOfStrings=openSomehowPythonInterpreter(“~/pythoncode.py”,“proc
var tag=document.getElementsByTagName(“p”)[0];
text=tag.innerHTML;
//这里我想用Python函数调用Python解释器
arrOfStrings=openSomehowPythonInterpreter(“~/pythoncode.py”,“processparagration(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)
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);
}
});
}
从
document.getElementsByTagName
我猜您是在浏览器中运行javascript
向浏览器中运行的javascript公开功能的传统方法是使用AJAX调用远程URL。AJAX中的X表示XML,但是现在每个人都使用JSON而不是XML
例如,使用jQuery可以执行以下操作:
$.getJSON('http://example.com/your/webservice?param1=x¶m2=y',
function(data, textStatus, jqXHR) {
alert(data);
}
)
您需要在服务器端实现python Web服务。对于我喜欢使用的简单Web服务
典型的实现如下所示:
@app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
您可以使用在浏览器中运行IronPython(类似于Python.Net),但我不知道NLTK是否可用于IronPython。通常,您可以使用类似
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();
您只需向pythoncode发出ajax请求。 您可以使用jquery来实现这一点,也可以只使用javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
没有Python程序,您无法从JavaScript运行.py文件,就像没有文本编辑器无法打开.txt文件一样。但是,在Web API服务器(下面的示例中为IIS)的帮助下,整个过程变得轻松起来
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()
[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();
}
import nltk # is not in JavaScript
def processParagraph(text):
...
nltk calls
...
return lst # returns a list of strings (will be converted to JavaScript array)
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);
}
});
}
请记住,.py文件不会在用户的计算机上运行,而是在服务器上运行。通过进程进行通信 例如: Python:此Python代码块应返回随机温度
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
Javascript(Nodejs):这里我们需要生成一个新的子进程来运行python代码,然后获得打印输出
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});
不,浏览器(幸运的是)不会执行任意Python代码。您需要在服务器上运行它。Javascript在客户端上运行。我假设python在服务器上运行。您可以向服务器发送ajax请求。它不会很快。使用ajax,将文本发送到服务器上的python脚本。将脚本设置为以易于解析(对于js)的表示法(如JSON)返回数据,并将结果分配给成功处理程序中的arrofstring。您可以通过使用clang和编译在浏览器中运行官方Python解释器。这是以前做过的。@FredFoo,如果浏览器没有运行ECMAScript(出于可疑的历史原因被称为JavaScript),那么实际上是幸运的。如果浏览器运行了一个安全的子集,那么也是幸运的(这就是任何人在浏览器中运行任何东西的意思,尽管是你的替罪羊)从90年代起,我们就开始使用Python,这样我们就不必处理当前的网络混乱。这看起来很有趣。哪里可以调用
processparagration(text)
,以便返回值以变量arrOfStrings
结尾?我在firebug中运行代码,但它记录[]
OK,那么它是如何正确的呢?我的Python文件包含正确的函数。我是否应该在Python中调用该函数,参数为sys.argv[1]?谢谢您的回答,但是为了让Python脚本执行,它必须由通过CGI或WSGI支持它的web服务器部署。你能在你的答案中包括如何解决这个问题吗?哦,如果我知道如何解决这个问题,我很乐意编辑你的答案,我希望你能提供一些建议,因为我发现这个错误XMLHttpRequest无法加载文件:~/pythoncode.py。跨源请求仅支持协议方案:http、数据、chrome扩展、https、chrome扩展资源
,即使我了解问题所在,也不知道如何解决。有有用的指针吗?谢谢。(顺便说一句,chessheaven看起来真是太棒了!我一定会试试看,幸好你在个人资料中放了一个可爱的女孩;)