我希望实现的目标与 this 非常相似。
我的实际目标是从 Python 中运行 Rasa。 从 Rasa 的网站获取:
Rasa 是构建对话软件的框架:Messenger/Slack 机器人、Alexa 技能等。在本文档中,我们将其缩写为 bot。
它基本上是一个在命令提示符中运行的聊天机器人。这是它在 cmd 上的工作方式:
现在我想从 Python 中运行 Rasa,以便将其与基于 Django 的网站集成。也就是说,我想继续接收用户输入,将其传递给 rasa,rasa 处理文本并给我输出,然后我将其显示回给用户。
我已经尝试过这样做(目前还是从 cmd 运行)。
import sys
import subprocess
from threading import Thread
from queue import Queue, Empty # python 3.x
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
queue.put(line)
out.close()
def getOutput(outQueue):
outStr = ''
try:
while True: #Adds output from the Queue until it is empty
outStr+=outQueue.get_nowait()
except Empty:
return outStr
p = subprocess.Popen('command_to_run_rasa',
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=False,
universal_newlines=True,
)
outQueue = Queue()
outThread = Thread(target=enqueue_output, args=(p.stdout, outQueue))
outThread.daemon = True
outThread.start()
someInput = ""
while someInput != "stop":
someInput = input("Input: ") # to take input from user
p.stdin.write(someInput) # passing input to be processed by the rasa command
p.stdin.flush()
output = getOutput(outQueue)
print("Output: " + output + "\n")
p.stdout.flush()
但它仅适用于第一行的输出。对于连续的输入/输出循环无效。请参见下面的输出。
如何使其在多个周期内工作?我参考了this,我认为从中理解了我的代码问题,但我不知道该如何解决它。
编辑:我正在Windows 10上使用Python 3.6.2(64位)