簡體   English   中英

Python中基於Twisted的簡單管理應用程序掛起並且不發送數據

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

您好,我正在嘗試編寫一個簡單的管理應用程序,當我連接到服務器時,它可以讓我訪問計算機外殼的telnet(這僅是python編程實踐的測試),然后終端(Windows telnet客戶端)只有黑屏,但在我程序的日志中有子程序的outpu形式,它並沒有發送到客戶端。我已經在Google上搜索了很多解決方案,但是它們都無法與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

您將阻止程序與非阻止程序混合在一起。 非阻塞部分無法運行,因為阻塞部分正在阻塞。 阻塞部分不起作用,因為它們依賴於運行的非阻塞部分。

擺脫Popen以及QueueThread ,改用reactor.spawnProcess 或者擺脫Twisted,並使用更多線程進行網絡連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM