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



我正试图创建一个执行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。">

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

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

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

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

最新更新