Python 中基于 Twisted 的简单管理应用程序挂起并且不发送数据

Simple Administrative Application in Python based on Twisted hangs and does not send data

你好,我正在尝试编写一个简单的管理应用程序,让我可以访问计算机 shell trought telnet(这只是测试 python 编程实践)当我连接到我的服务器时,然后我终端(Windows telnet 客户端)只有黑屏,但在我的程序日志中有子进程的输出,它不会发送到客户端 我在 Google 上搜索了许多解决方案,但其中 none 正确地使用了 Twisted lib,结果是相同的

我的服务器代码:

# -*- 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

您将阻塞程序与非阻塞程序混合使用。非阻塞部分不会到达 运行 因为阻塞部分正在阻塞。阻塞部分不起作用,因为它们依赖于非阻塞部分 运行ning.

去掉 PopenQueue 以及 Thread 并使用 reactor.spawnProcess 代替。或者摆脱 Twisted 并为网络使用更多线程。