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

在Electron中,仅在python脚本执行结束时接收到PythonShell消息,python,node.js,electron,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) { con

我正在尝试创建一个执行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

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

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

所以我把我的代码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

我不知道是否还有其他更好的解决方案,但有了这个解决方案,它就可以了。好的,我在github论坛上找到了这个答案

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

所以我把我的代码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

我不知道是否还有其他更好的解决方案,但有了这个解决方案,它就可以工作了

请在Python的打印函数中使用flush

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

请在Python的打印函数中使用flush

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