基于Twisted的简单管理应用程序挂起并且不发送数据
问题描述:
您好,我正在尝试编写一个简单的管理应用程序,它使我能够访问计算机shell trought telnet(这只是测试python编程实践)当我连接到我的服务器,然后我只在终端(Windows远程登录客户端)黑屏,但在我的程序日志有输出形式的子进程,它sdoes没有被发送到客户端 我已经搜索了谷歌的许多解决方案,但没有一个工作与扭曲的LIB适当,结果是一样的基于Twisted的简单管理应用程序挂起并且不发送数据
我的服务器代码:
# -*- coding: utf-8 -*-
from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue # Python 2
from twisted.internet import reactor
from twisted.internet.protocol import Factory
from twisted.protocols.basic import LineReceiver
import sys
log = 'log.tmp'
def reader(pipe, queue):
try:
with pipe:
for line in iter(pipe.readline, b''):
queue.put((pipe, line))
finally:
queue.put(None)
class Server(LineReceiver):
def connectionMade(self):
self.sendLine("Creating shell...")
self.shell = Popen("cmd.exe", stdout=PIPE, stderr=PIPE, bufsize=1, shell=True)
q = Queue()
Thread(target=reader, args=[self.shell.stdout, q]).start()
Thread(target=reader, args=[self.shell.stderr, q]).start()
for _ in xrange(2):
for pipe, line in iter(q.get, b''):
if pipe == self.shell.stdout:
sys.stdout.write(line)
else:
sys.stderr.write(line)
self.sendLine("Shell created!")
def lineReceived(self, line):
print line
#stdout_data = self.shell.communicate(line)[0]
self.sendLine(line)
if __name__ == "__main__":
ServerFactory = Factory.forProtocol(Server)
reactor.listenTCP(8123, ServerFactory) #@UndefinedVariable
reactor.run() #@UndefinedVariable
答
您将阻塞程序与非阻塞程序混合使用。由于阻塞部件阻塞,非阻塞部件无法运行。阻塞部件不工作,因为它们依赖于运行的非阻塞部件。
摆脱Popen
和Queue
和Thread
并使用reactor.spawnProcess
来代替。或者摆脱扭曲并使用更多线程进行联网。