我正在尝试创建一个nw.js应用程序,该应用程序使用节点模块PythonShell与Python通信。
我遇到的问题是,除非我关闭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?
发布于 2017-02-27 22:47:42
有几个问题:
sys.stdin.readline()而不是sys.stdin.readlines()。否则,Python将继续等待您完成输入流。您应该能够发送一个^D信号来终止输入的结束,但这对我来说是行不通的。同样重要的是:
\n,但输出不会。无论出于什么原因,输出都需要\n和sys.stdout.flush()来工作;其中一个或另一个不会削减它。下面是工作的完整示例代码:
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控制台中立即接收响应!
https://stackoverflow.com/questions/42462072
复制相似问题