xra*_*alf 70 javascript python integration function
我想~/pythoncode.py从~/pythoncode.py代码中调用一个函数,因为没有其他方法~/pythoncode.py来做我想做的事情.这可能吗?你能调整下面的片段吗?
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)");
Run Code Online (Sandbox Code Playgroud)
包含使用高级库的函数,这些库在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)
Run Code Online (Sandbox Code Playgroud)
Sal*_*ali 46
您只需要对pythoncode发出ajax请求即可.您可以使用jquery http://api.jquery.com/jQuery.ajax/执行此操作,或仅使用javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
Run Code Online (Sandbox Code Playgroud)
Pau*_*ine 24
从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);
}
)
Run Code Online (Sandbox Code Playgroud)
您需要在服务器端实现python Web服务.对于简单的Web服务,我喜欢使用Flask.
典型的实现如下:
@app.route("/your/webservice")
def my_webservice():
return jsonify(result=some_function(**request.args))
Run Code Online (Sandbox Code Playgroud)
您可以在浏览器中使用silverlight运行IronPython(某种Python.Net),但我不知道NLTK是否适用于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();
Run Code Online (Sandbox Code Playgroud)
如果没有 Python 程序,您就无法从 JavaScript 运行 .py 文件,就像没有文本编辑器就无法打开 .txt 文件一样。但在 Web API 服务器(下例中的 IIS)的帮助下,整个事情变得轻而易举。
安装python并创建示例文件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()
Run Code Online (Sandbox Code Playgroud)在您的 Web API 服务器中创建一个方法
[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();
}
Run Code Online (Sandbox Code Playgroud)现在来看看你的 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);
}
});
}
Run Code Online (Sandbox Code Playgroud)请记住,您的 .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='')
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
173357 次 |
| 最近记录: |