首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >节点中的PythonShell (nwjs)

节点中的PythonShell (nwjs)
EN

Stack Overflow用户
提问于 2017-02-25 21:59:16
回答 1查看 1.8K关注 0票数 3

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

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

以下是我的剧本:

script.py

代码语言:javascript
复制
import sys

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

if __name__ == '__main__':
    main()

main.js

代码语言:javascript
复制
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?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-02-27 22:47:42

有几个问题:

  • 使用sys.stdin.readline()而不是sys.stdin.readlines()。否则,Python将继续等待您完成输入流。您应该能够发送一个^D信号来终止输入的结束,但这对我来说是行不通的。
  • 为了保持流打开,将命令行输入封装在一个循环中(请参阅下面的Python代码)

同样重要的是:

  • 输入会自动追加\n,但输出不会。无论出于什么原因,输出都需要\nsys.stdout.flush()来工作;其中一个或另一个不会削减它。
  • 似乎缓存了Python代码。因此,如果对Python文件进行任何更改,则必须重新启动nwjs应用程序才能生效。

下面是工作的完整示例代码:

script.py

代码语言:javascript
复制
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()

main.js

代码语言:javascript
复制
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控制台中立即接收响应!

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42462072

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档