nodejs + express 调用本地 python程序

假设已经安装好 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 读取文本文件




 
 python draw flowers
 


 
turtle 画一朵花    源代码
turtle 画一朵玫瑰花 源代码
turtle 画一朵西兰花 源代码

 

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

运行 node server.js

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

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

你可能感兴趣的:(javascript,nodejs,jquery,nodejs,express)