【问题标题】:PythonShell messages received only at the end of the python script execution in ElectronPythonShell 消息仅在 Electron 中的 python 脚本执行结束时收到
【发布时间】:2020-07-04 13:35:10
【问题描述】:

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

【问题讨论】:

    标签: python node.js electron


    【解决方案1】:

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

    “输出可能被缓冲了,这意味着你没有发送足够的数据来刷新缓冲区至少一次。关闭标准输入(通过结束进程)强制缓冲区刷新,导致你的应用程序接收数据。这很常见,您通常不希望写入每个字节,因为它会占用过多的 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
    

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2021-09-25
        • 1970-01-01
        • 2019-06-27
        • 1970-01-01
        • 1970-01-01
        • 2017-10-16
        • 2021-11-06
        • 2019-09-23
        • 1970-01-01
        相关资源
        最近更新 更多