Node 中的 PythonShell (nwjs)

标签 python node.js nw.js

我正在尝试创建一个使用 Node 模块 PythonShell 与 Python 通信的 nw.js 应用程序。

我遇到的问题是,除非我关闭标准输入,否则不会向控制台写入任何内容。但是,我想保持流打开,以便我可以向 Python 脚本发送多个命令,并让 Python 保存其状态。

这是我的脚本:

脚本.py

import sys

def main():
    command = sys.stdin.readlines()  # unused for now
    sys.stdout.write("HELLO WORLD")
    sys.stdout.flush()

if __name__ == '__main__':
    main()

主要.js

var PythonShell = require('python-shell');
var pyshell = new PythonShell('script.py');

pyshell.on('message', function (message) {
  console.log(message);
});

pyshell.send('hello');

此时,什么也没有发生。

如果我执行 pyshell.end(),那么 HELLO WORLD 会输出到控制台。但后来我无法发出进一步的 pyshell.send 命令。

如何让 Python 子进程保持运行并等待输入,同时将所有输出通过管道返回给 JS?

最佳答案

几个问题:

  • 使用 sys.stdin.readline() 而不是 sys.stdin.readlines()。否则,Python 将继续等待您完成输入流。您应该能够发送一个 ^D 信号来终止输入的结尾,但这对我不起作用。

  • 要保持流打开,将命令行输入包装在一个循环中(参见下面的 Python 代码)

同样重要的是:

  • 输入会自动附加 \n,但输出不会。无论出于何种原因,输出都需要 \nsys.stdout.flush() 才能工作;一个或另一个不会削减它。

  • Python-shell 似乎可以缓存您的 Python 代码。因此,如果您对 Python 文件进行了任何更改,则必须重新启动 nwjs 应用程序才能使其生效。

这是完整的示例代码:

脚本.py

import sys

def main():
    while True:
        command = sys.stdin.readline()
        command = command.split('\n')[0]
        if command == "hello":
            sys.stdout.write("You said hello!\n")
        elif command == "goodbye":
            sys.stdout.write("You said goodbye!\n")
        else:
            sys.stdout.write("Sorry, I didn't understand that.\n")
        sys.stdout.flush()

if __name__ == '__main__':
    main()

主要.js

var PythonShell = require('python-shell');
var pyshell = new PythonShell('script.py');

pyshell.on('message', function (message) {
  console.log(message);
});

pyshell.send('hello');

现在使用 pyshell.send("hello")pyshell.send("goodbye")pyshell.send("garbage") 并在 JS 控制台中立即收到响应!

关于 Node 中的 PythonShell (nwjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42462072/

相关文章:

javascript - 播放列表项目的视频长度 Webchimera.js Player

nw.js - 如何使用nwjc命令?

python - 使用 sympy 反转函数并评估反转函数给了我一个错误的答案

javascript - 服务器端串行通过 python Tornado 聊天

javascript - 如何在响应和请求中添加新方法

node.js - 编剧:从不能使用 page.setInputFiles 的非输入元素上传文件?

javascript - 如何在 Windows 上打包 NW.js 应用程序

python - 如何让 Python 同时对列表中的所有项目进行循环?

python - 与内置指纹传感器 Python 接口(interface)

javascript - Node |要求未定义