我正在尝试创建一个使用 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
,但输出不会。无论出于何种原因,输出都需要\n
和sys.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/