在node.js

时间:2018-01-21 17:54:27

标签: javascript python node.js

我正在使用节点服务器来运行python脚本。我正在使用Python shell包来运行它们,这很好用。这是在我正在运行的server.js文件中:

app.get('/start/:fileName', function(req, res) {  
  let fileName = req.params.fileName;
  console.log(fileName)
  PythonShell.run(`./python_scripts/${fileName}`, function (err,results) {
    console.log('results ',results);
    if (err) throw err;
    console.log('finished');
  });
});

在另一个文件main.js中,我有命令:

function fetchStartEndpoint(fileName) {
  fetch(`/start/${fileName}`)
    .catch(error => console.log(error));
}``

单击按钮时,我会调用fetchStartEndpoint

这一切都运行正常,但我想使用多个按钮来运行多个脚本。单击按钮时,脚本会运行,但是当我单击其他按钮运行不同的脚本时,第一个脚本会继续运行。我希望它结束​​并运行第二个。有没有办法覆盖初始脚本并运行第二个脚本而不是重新启动服务器?

1 个答案:

答案 0 :(得分:1)

我正在python-shell快速浏览自述文件​​,在我看来,在shell实例上调用end是停止运行脚本的方法:

运行(脚本,选项,回调)

此方法也返回PythonShell实例。

.END(回调)

关闭stdin流,允许Python脚本完成并退出。当进程终止时,将调用可选的回调。

基于此,我认为这可行:

// First button pressed ... 
var shell = PythonShell.run('script.py', function (err, results) {
   // script finished 
   shell = null
});

// Second button pressed ... 
if (shell) {

    shell.end(function() {
       // start second script ...
    })
}