nodejs + express 调用本地 python程序

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

假设已经安装好 nodejs ;

cd /js/node_js ; 安装在当前目录的 node_modules/

npm install express --save 

或者 cnpm install express --save

web 服务器程序 server.js

const http = require('http');
const express = require('express');
const path = require('path');
const app = express();
const exec = require('child_process').exec;
var server_info = '\nServer running at http://127.0.0.1:8000/  (CTRL+C to stop)';

function run_command(command) {
    console.log("\n" + command);
    exec(command, (err, stdout, stderr) => console.log(stdout, server_info));
}
// 静态文件路径
app.use(express.static('public'));

app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

app.get('/draw_flower1', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
    res.redirect('/');
    run_command("pythonw /python/draw_flower1.py");
});

app.get('/draw_rose1', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
    res.redirect('/');
    run_command("pythonw /python/draw_rose1.py");
});

app.get('/draw_xilan1', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
    res.redirect('/');
    run_command("pythonw /python/draw_xilan1.py");
});

app.listen(8000, "127.0.0.1", function() {
    console.log(server_info);
});

index.html  用 jQuery.ajax 读取文本文件

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>python draw flowers</title>
 <script src="jquery-3.2.1.min.js"></script>
</head>
<body>
 <div class="container">
  turtle 画一朵花    <a href="#" onclick="readfile('draw_flower1.py');">源代码 </a>
  <form method="put" action="/draw_flower1">
    <input type="submit" value="运行 draw_flower1.py">
  </form>
  turtle 画一朵玫瑰花 <a href="#" onclick="readfile('draw_rose1.py');">源代码 </a>
  <form method="put" action="/draw_rose1">
    <input type="submit" value="运行 draw_rose1.py">
  </form>
  turtle 画一朵西兰花 <a href="#" onclick="readfile('draw_xilan1.py');">源代码 </a>
  <form method="put" action="/draw_xilan1">
    <input type="submit" value="运行 draw_xilan1.py">
  </form>
 </div>
 <p>
 <pre id="code"> </pre>
 </p>
<script type="text/javascript">
/**
 * 利用 ajax 读取文本文件
 * @param {文件路径} url 
 */
  function readfile(url){
    $.ajax({
        url: url, // 文本文件位置
        type: "GET", // 请求方式为 get
        async: false,
        dataType: "text", // 返回数据格式为 text
        success: function(data) { //请求成功完成后要执行的方法 
            $('#code').html(data);
        }
    })
  }
</script>
</body>
</html>

jquery.min.js , python 程序要放在 public/

运行 node server.js

浏览器访问 http://127.0.0.1:8000/

参考旧版本python : html 调用本地python程序

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: NodeJSpython