2

我正在尝试使用我在 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');
});

指数.pug

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

2 回答 2

4

创建另一个您将在单击按钮时调用的路由。让我们称之为/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 创建按钮。/foo在您的客户端 javascript 中,在单击此按钮时进行 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
于 2018-02-12T13:53:12.413 回答
-1

让我们来看看。通常我为了与 python/nodejs 交互,我使用 djangorestframework,它使用服务器方法 GET、POST 等。所以首先你必须在 python 中有一个正在运行的服务器和脚本。然后在节点中,您可以使用 jquery 或 js 框架来侦听节点应用程序中的事件。单击按钮时,将向 python 发送获取/发布请求。在 python 中,您还可以使用 javascript 对脚本进行条件渲染,例如: if request == POST: //run script。由于脚本是从节点运行的,因此您必须在单击按钮时通过节点中的 http 触发事件。只是一个想法。

于 2018-02-12T13:35:33.780 回答