仅在Electron中的python脚本执行结束时收到PythonShell消息

时间:2020-03-24 03:29:54

标签: python node.js electron

我正在尝试创建一个执行Python脚本的Electron应用程序,但是在脚本结束之前无法从python检索消息。

这是文件main.js开头的代码:

const { PythonShell } = require('python-shell');

let pyshell = new PythonShell('app.py');

console.log("MAIN: Script started")

pyshell.on('message', function (message) {
  console.log("Message from APP: " + message);
});

// end the input stream and allow the process to exit
pyshell.end(function (err, code, signal) {
  if (err) throw err;
  console.log('The exit code was: ' + code);
  console.log('The exit signal was: ' + signal);
  console.log('finished');
});

let seconds = 0
setInterval(function(){ 
  seconds = seconds + 5
  console.log("MAIN: " + seconds + " seconds"); }, 5000);

这是python脚本:

import sys
import time

print("START")
time.sleep(10)
print("After 10 seconds")

这是外壳:

MAIN: Script started
MAIN: 5 seconds
MAIN: 10 seconds
Message from APP: START
Message from APP: After 10 seconds
The exit code was: 0
The exit signal was: null
finished
MAIN: 15 seconds

2 个答案:

答案 0 :(得分:0)

好吧,我在github论坛上找到了这个答案。

“输出可能正在缓冲,这意味着您没有发送足够的数据来至少刷新一次缓冲区。关闭stdin(通过结束进程)会强制刷新缓冲区,从而导致您的应用程序接收数据。这很常见,您通常不希望写每个字节,因为这会占用大量IO。”

https://github.com/extrabacon/python-shell/issues/8

所以我将代码app.py代码更改为

import sys
import time

print("START")
sys.stdout.flush()
time.sleep(10)
print("After 10 seconds")

现在输出正确了

MAIN: Script started
Message from APP: START
MAIN: 5 seconds
MAIN: 10 seconds
Message from APP: After 10 seconds
The exit code was: 0
The exit signal was: null
finished
MAIN: 15 seconds

我不知道是否还有其他更好的解决方案,但是有了这个解决方案,

答案 1 :(得分:0)

请在Python的打印功能中使用冲洗

print('Python started from NODE.JS', flush=True)