Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python telnetlib模块:读取并等待响应_Python_Response_Wait_Telnetlib - Fatal编程技术网

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

python telnetlib模块:读取并等待响应,python,response,wait,telnetlib,Python,Response,Wait,Telnetlib,我遇到了与此海报类似的问题: 注意下面的回复和我的回复 本质上,telnetlib不允许我在调用任何read函数时读取整个响应 在使用select.select后调用telnet.read\u时,在while循环中选择[telnetobject],[],以确保读取可用,我只会得到几个字符。到目前为止,我能想出的唯一解决办法是利用时间。睡眠,但这是一个太粗糙的解决方案,我正在寻找更适合的。感谢您的帮助……我想我也遇到了同样的问题,我希望这些信息能有所帮助。在我的例子中,我正在连接Maya中的mel

我遇到了与此海报类似的问题:

注意下面的回复和我的回复

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


在使用select.select后调用telnet.read\u时,在while循环中选择[telnetobject],[],以确保读取可用,我只会得到几个字符。到目前为止,我能想出的唯一解决办法是利用时间。睡眠,但这是一个太粗糙的解决方案,我正在寻找更适合的。感谢您的帮助……

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

向我展示了我尝试执行的I/O根本不需要Telnet/telnetlib,并推荐了它

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

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

telnetlib似乎不会对写入进行排队。因此,我计划将两个命令背靠背地发送到真正的命令,然后命令完整公告并不总是有效。因此,似乎只有当您确切地知道要读取的输出,或者在怀疑输出完成之前愿意睡觉时,才可以读取telnetlib输出。但是,asynchat.push肯定会按预期的方式进行写入。 一个样本,要用一大粒盐来采集,因为我还在想这个问题:

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 = []

派对迟到了,但这在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')
或者,如果您总是想等待响应:

try:
    message = session.read_until(b'\n') # Will not timeout until you have response
    print(message)
    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')