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

标签 javascript python node.js pug pugjs

我正在尝试使用我在 pug 中创建的网页运行 python 脚本,在 Node 中表达。我对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');
});

索引.pug

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

最佳答案

创建另一条在单击按钮时将调用的路线。我们称之为/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
    })
})

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

button(type="button", onclick="makeCallToFoo()") Run python script

在你的客户端 JS 中:

function makeCallToFoo() {
    fetch('/foo').then(function(response) {
        // Use the response sent here
    })
}

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

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

关于javascript - Node如何在使用pug和express Node网站单击按钮时运行python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48707021/

相关文章:

javascript - 当 AngularJS 的 bool 值为 TRUE 时显示图像(或图标)?

node.js - mongodb 实现中的嵌套文档,就像 Reddit 评论一样

javascript - 监听 http 80 端口时出现 Node.js EACCES 错误(权限被拒绝)

python - 将数据框与 Excel 中的行进行比较

python - 如何在调用 gnuplot 时保持 PyQt5 响应?

python - 重现次数

angularjs - 如何测试使用 MEAN 堆栈 API 的 Angular 前端

javascript - 每日 javascript 倒计时缩短为 jquery

javascript - dwr addoptions 与关联数组

javascript - 将值连接到嵌套的 JavaScript 对象