如何使用JS调用Python脚本


本文将详细介绍通过JS调用Python脚本的方法,包括使用Node.js、Python shell、child_process等三种方法,以及在Web应用中的应用。

一、使用Node.js

Node.js是一个可以在服务器端运行JS脚本的平台,可以通过child_process模块的spawn方法来执行Python脚本。

 const { spawn } = require('child_process');
 const pyScript = spawn('python', ['script.py']);

 pyScript.stdout.on('data', (data) => {
   console.log(`stdout: ${data}`);
 });

 pyScript.stderr.on('data', (data) => {
   console.error(`stderr: ${data}`);
 });

 pyScript.on('close', (code) => {
   console.log(`Python script exited with code ${code}`);
 });

上述代码通过spawn()方法调用Python脚本,将Python脚本的输出打印到控制台。我们也可以在Python脚本中使用print来输出结果,然后在JS中获取到结果。

二、使用Python Shell

Python Shell是一个基于Node.js的模块,可以在JS中直接调用Python脚本。

 const { PythonShell } = require('python-shell');

 PythonShell.run('script.py', null, (err, results) => {
   if (err) throw err;
   console.log('Python script finished.');
   console.log('Results:', results);
 });

上述代码通过PythonShell.run()方法调用Python脚本,将结果打印到控制台。

三、使用child_process

除了使用Node.js的spawn方法,我们还可以使用child_process模块的exec方法来调用Python脚本。

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

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

四、Web应用中的应用

在Web应用中,我们可以使用Node.js的Express框架来接收HTTP请求,并使用child_process模块来调用Python脚本。

 const express = require('express');
 const { spawn } = require('child_process');

 const app = express();

 app.get('/', (req, res) => {
   const pyScript = spawn('python', ['script.py', arg1, arg2]);

   pyScript.stdout.on('data', (data) => {
      res.send(data.toString());
   });

   pyScript.stderr.on('data', (data) => {
      res.status(500).send(data.toString());
   });

   pyScript.on('close', (code) => {
      console.log(`Python script exited with code ${code}`);
   });
});

 app.listen(3000, () => {
   console.log('Server is running on port 3000');
 });

上述代码通过Express框架创建了一个HTTP服务器,当服务器接收到GET请求时,将会执行Python脚本,并将Python脚本的结果以HTTP响应的形式返回到客户端。

总结

通过本文的介绍,我们可以学习到使用Node.js、Python Shell、child_process等多种方法来调用Python脚本,并且可以将它应用到Web开发中。

评论关闭