欢迎光临
我们一直在努力

js如何调用python

JS 调用 Python 的方法

简介

在 web 开发中,有时需要在 javascript (js) 代码中调用 python 代码以扩展 js 的功能或访问 python 特有的库和数据源。本篇文章将介绍几种在 js 中调用 python 的方法。

使用 Node.js

Node.js 是一个流行的 JavaScript 运行时环境,它允许你在服务器端执行 JavaScript 代码。在 Node.js 中,可以使用 child_process 模块调用 Python 代码。以下是一个示例:

const { exec } = require('child_process');

exec('python script.py', (error, stdout, stderr) => {
  if (error) {
    console.error(`error: ${error.message}`);
    return;
  }

  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

使用 WebAssembly

WebAssembly (WASM) 是一种二进制格式,允许在 Web 浏览器中运行编译后的代码。你可以使用 Python 编译器(如 Emscripten)将 Python 代码编译成 WASM 模块,然后在 JS 代码中加载和调用它。以下是一个示例:

fetch('script.wasm')
  .then(response => response.arrayBuffer())
  .then(buffer => WebAssembly.instantiate(buffer))
  .then(({ instance }) => {
    // 调用 Python 函数
    const result = instance.exports.my_python_function();
    console.log(result);
  });

使用 Python 脚本服务器

另一种方法是在服务器端运行一个 Python 脚本服务器,并使用 AJAX 调用(如 XMLHttpRequest)从 JS 代码向该服务器发送请求。以下是一个 Python 服务器示例:

import flask

app = flask.Flask(__name__)

@app.route('/my_python_function', methods=['POST'])
def my_python_function():
    data = flask.request.get_json()
    result = my_python_function(data)
    return flask.jsonify({'result': result})

app.run()

在 JS 中,你可以使用 XMLHttpRequest 发送请求并接收响应:

立即学习Python免费学习笔记(深入)”;

const xhr = new XMLHttpRequest();
xhr.open('POST', '/my_python_function');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
  const result = JSON.parse(xhr.responseText).result;
  console.log(result);
};
xhr.send(JSON.stringify({ ... }));
赞(0) 打赏
未经允许不得转载:码农资源网 » js如何调用python
分享到

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册