我正在尝试使用节点模块PythonShell创建一个与Python通信的nw.js应用程序。
我遇到的问题是除非我关闭stdin,否则不会向控制台写入任何内容。但是我想保持流打开,以便我可以向Python脚本发送多个命令,并让Python保存其状态。
以下是我的脚本:
script.py
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
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?
答案 0 :(得分:4)
有几个问题:
使用sys.stdin.readline()
代替sys.stdin.readlines()
。否则,Python将继续等待您完成输入流。您应该能够发送^D
信号以终止输入结束,但这对我不起作用。
要保持流打开,请将命令行输入包装在循环中(请参阅下面的Python代码)
同样重要的是:
输入会自动附加\n
,但输出不会。无论出于何种原因,输出都需要\n
和sys.stdout.flush()
才能工作;一个或另一个不会削减它。
Python-shell似乎缓存了你的Python代码。因此,如果对Python文件进行任何更改,则必须重新启动nwjs应用程序才能使其生效。
以下是完整的示例代码:
script.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()
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控制台中立即收到响应!