Node如何在使用pug和express Node网站单击按钮时运行python脚本

Sam*_*Sam 2 javascript python node.js pugjs pug

我正在尝试使用我在 pug 中创建的网页运行 python 脚本,在节点中表达。我对python比node更熟悉。使用下面的内容如何运行 python 脚本?我包含 python shell,但不确定当我单击 pug 网页上的按钮时如何运行 python 脚本。

服务器.js

// require all dependencies
var express = require('express');
var app = express();
var PythonShell = require('python-shell');


// set up the template engine
app.set('views', './views');
app.set('view engine', 'pug');

var options = {
  mode: 'text',
  pythonOptions: ['-u'],
  scriptPath: '../hello.py',
  args: ['value1', 'value2', 'value3']
};



// GET response for '/'
app.get('/', function (req, res) {

    // render the 'index' template, and pass in a few variables
    res.render('index', { title: 'Hey', message: 'Hello' });

PythonShell.run('hello.py', options, function (err, results) {
    if (err) throw err;
    // results is an array consisting of messages collected during execution
    console.log('results: %j', results);
});

});

// start up the server
app.listen(3000, function () {
    console.log('Listening on http://localhost:3000');
});
Run Code Online (Sandbox Code Playgroud)

索引.pug

html
    head
        title= title
    body
        h1= message
        a(href="http://www.google.com"): button(type="button") Run python script
Run Code Online (Sandbox Code Playgroud)

ayu*_*hgp 5

创建另一条在单击按钮时将调用的路线。我们称之为/foo。现在为此路由设置处理程序:

const { spawn } = require('child_process')
app.get('/foo', function(req, res) {
    // Call your python script here.
    // I prefer using spawn from the child process module instead of the Python shell
    const scriptPath = 'hello.py'
    const process = spawn('python', [scriptPath, arg1, arg2])
    process.stdout.on('data', (myData) => {
        // Do whatever you want with the returned data.
        // ...
        res.send("Done!")
    })
    process.stderr.on('data', (myErr) => {
        // If anything gets written to stderr, it'll be in the myErr variable
    })
})
Run Code Online (Sandbox Code Playgroud)

现在在前端使用 pug 创建按钮。/foo在您的客户端 JavaScript 中,单击此按钮时进行 AJAX 调用。例如,

button(type="button", onclick="makeCallToFoo()") Run python script
Run Code Online (Sandbox Code Playgroud)

在你的客户端 JS 中:

function makeCallToFoo() {
    fetch('/foo').then(function(response) {
        // Use the response sent here
    })
}
Run Code Online (Sandbox Code Playgroud)

编辑:您还可以以类似的方式使用已经使用的 shell 模块。如果您不需要客户端 JS,您可以将按钮包含在具有以下属性的表单中:method="get" action="/foo"。例如,

form(method="get" action="/foo")
    button(type="submit") Run python script
Run Code Online (Sandbox Code Playgroud)