通过nodejs执行python脚本

我试图执行这段执行python脚本的节点js代码。 通过这个代码工作正常。 但是立即在前端显示“运行”和“结束”的响应。 一旦python脚本的执行完成,就必须显示“finshed”。

app.post('/execute', function(request, response){ response.write("running"); console.log("executing") var pyshell = new PythonShell('./python_codes/test.py') pyshell.on('message', function (message) {console.log(message);}); pyshell.end(function (err) {if (err){throw err;};console.log('finished');}); response.write("finished"); response.end(); }); 

您应该在callback函数中添加您的响应

 app.post('/execute', function(request, response){ response.setHeader('Connection', 'Transfer-Encoding'); response.setHeader('Content-Type', 'text/html; charset=utf-8'); response.write("running"); console.log("executing") var pyshell = new PythonShell('./python_codes/test.py') pyshell.on('message', function (message) {console.log(message);}); pyshell.end(function (err) { if (err){ throw err; }; console.log('finished'); response.write("finished"); response.end(); }); }); 

发生这种情况是因为PythonShell类是asynchronous的。 你的代码正在做的是创build一个PythonShell对象,将其存储在variablespyshell ,然后将一些事件添加到pyshell对象。 然后直接继续写“完成”。

因为写入“完成”不是end()函数callback的一部分,所以它马上就会发生。 我至less有三件事可以做:

  1. 如果您使用的HTTP库支持它,只需添加response.write("finished"); response.end(); response.write("finished"); response.end(); 代码到pyshell.endcallback。
  2. 使用支持暂停当前执行线程的库(或使用execSync )来调用Python。 这是不好的做法,因为它违背了使用像node.js这样的并发框架的目的,但是会起作用。
  3. 使用WebSockets(或者即使WebSocket不可用(例如通过CloudFlare)也可以工作的socket.io )来传输“已完成”消息。