我想使用subprocess.Popen()来执行一个C程序,并实时输出它的输出并将它发送给客户端。但是,输出缓冲并在执行结束时一起发送(Blocking性质)。我怎样才能实时接收输出,然后立即将其发送到Twisted Autobahn中。如何在Twisted [autobahn] websocket服务器中实时流式输出?
def onConnect(self, request):
try:
self.cont_name = ''.join(random.choice(string.lowercase) for i in range(5))
self.file_name = self.cont_name
print("Connecting...")
except Exception:
print("Failed"+str(Exception))
def onOpen(self):
try:
print("open")
except Exception:
print("Couldn't create container")
def onMessage(self, payload,isBinary=False):
cmd = "docker exec "+self.cont_name+" /tmp/./"+self.file_name
a = subprocess.Popen([cmd], shell=True, stdout=subprocess.PIPE, bufsize=1)
for line in iter(a.stdout.readline, b''):
line = line.encode('utf8')
self.sendMessage(line)
def onClose(self, wasClean, code, reason):
try:
print("Closed container...")
except Exception:
print(str(Exception))
当使用子过程执行该命令搬运工,C代码的整个输出在一次,而不是因为它发生返回。对于前:
#include <stdio.h>
#include <unistd.h>
int main(){
int i=0;
for(i=0;i<5;i++){
fflush(stdout);
printf("Rounded\n");
sleep(3);
}
}
在容器中运行之后,程序应该在3秒到客户端返回“四舍五入”。然而,它最终会在执行结束时发送所有'Rounded'。
你的问题广义上讲是有道理的,但是*广泛地说,它不是很清楚你遇到的问题在哪里,或者有什么建议可以帮助你克服它。你可以包含一些示例代码吗?最好按照http://sscce.org/的说法。 –
@ Jean-PaulCalderone我添加了一些代码。请确认一下。谢谢 –