python telnetlib模块:读取并等待响应

2024-10-05 22:03:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我也有类似的问题:

Python telnetlib: surprising problem

注意下面的回答和我的回答。在

本质上,telnetlib不允许我在调用任何read函数时读取整个响应。在

打电话时telnet.read_非常渴望使用后()选择。选择([telnetobject],[])在while循环中,为了确保可以读取,我只能得到几个字符。到目前为止,我能想到的唯一解决方案是使用时间。睡觉()但这是一个太粗糙的解决方案,我正在寻找更适合的。感谢任何帮助。。。在


Tags: 函数read时间解决方案字符telnetproblemwhile
2条回答

派对迟到了,但这是可以用telnetlib实现的。下面将阅读所有的行,直到什么都没有留下。timeout=0.1增加响应到达的时间。在

try:
    while True:             # read until we stop
        message = session.read_until(b'\n', timeout=0.1)
        if message == b'':  # check if there was no data to read
            break           # now we stop
        print(message)      # print message if not stopped
except EOFError:            # If connection was closed
    print('connection closed')

或者如果您总是想等待响应:

^{pr2}$

我想我也有同样的问题,我希望这些信息能有所帮助。在我的例子中,我正在连接到Maya中的mel和python端口,因此我不知道此体验是否对您和您的情况有用。在

  • This answer向我表明我根本不需要Telnet/telnetlib来完成我要做的I/O,并建议使用asynchat

  • 结果显示,并非所有出现在服务器端的输出都可供客户端读取。在我使用asynchat作为第二种意见之前,我不知道会发生这种情况,并且看到无论如何发送,我仍然没有收到“print‘Complete Command’”的输出。(我试图写“print'Complete Command'”并读取结果,以了解我之前的命令何时完成。)

最后我调用了mel的warning命令,它确实生成了客户端可读的输出。发送无辜的数据作为警告是相当令人讨厌的,但幸运的是这是一个内部工具。在

  • telnetlib似乎不排队写入。因此,我计划发送两个命令背靠背(真正的命令,然后“命令完成”公告)并不总是有效的。因此,似乎只有当您确切地知道要读取_until()的输出,或者您愿意睡觉,直到您怀疑输出完成时,才能读取telnetlib输出。然而推送.asynchat()确实按预期排队写入。在

一个样本,在我还没弄清楚的时候,就拿了一大粒盐:

class mayaClient(asynchat.async_chat) :


... 

def __init__(self, sock, clientType):

    asynchat.async_chat.__init__(self, sock=sock)

    self.clientType = clientType
    self.ibuffer = []
    self.obuffer = ""
    self.set_terminator("\r\n")
    self.cumulativeResponse = ""


@classmethod
def withSocket(cls, host, clientType, log) :

    melSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    portNumber = cls.MEL_PORT_NUMBER if clientType == cls.MEL else cls.PYTHON_PORT_NUMBER
    melSocket.connect((host, portNumber))   
    return cls(melSocket, clientType, log)


#############################################################
# pushAndWait
#############################################################
def pushAndWait(self, command, timeout=60) :
    """
    ACTION:     Push a command and a "command complete" indicator
                If command completed, return number of milliseconds it took
                If command timed out without completing, return -1

    INPUT:      command as string
                description (optional) as string for more informative logging
                timeout in seconds as int after which to give up

    OUTPUT:     X milliseconds if command completed
                -1 if not

    """

    self.found_terminator()

    incrementToSleep = .001

    self.push("%s\r\n"%command)

    responseToSeek = "Command Complete"
    self.push('Whatever command is going to create readable output for %s`); \r\n'%responseToSeek)

    timeSlept = 0
    while responseToSeek not in self.currentBufferString() and timeSlept < timeout :
        self.read()
        timeSlept += incrementToSleep
        time.sleep(incrementToSleep)

    if responseToSeek in self.currentBufferString() :
        return timeSlept

    return -1


#############################################################
# read
#############################################################
def read(self) :
    """
    ACTION:     Reads the current available output
                and stores it in buffer

    """

    try :

        self.collect_incoming_data(self.recv(1024))

    except Exception, e :

        # Don't worry about it   just means there's nothing to read
        #
        pass


#############################################################
# currentBuffer
#############################################################
def currentBuffer(self) :

    return self.ibuffer


#############################################################
# currentBufferString
#############################################################
def currentBufferString(self) :

    return "".join(self.ibuffer)


#############################################################
# collect_incoming_data
#############################################################
def collect_incoming_data(self, data):
    """Buffer the data"""

    self.ibuffer.append(data)   


#############################################################
# found_terminator
#############################################################
def found_terminator(self):

    print "Clearing  %s...  from buffer"%self.currentBufferString()[0:20]
    self.ibuffer = []

相关问题 更多 >