Parmiko SFTP文件-调用.next()会立即导致StopIteration,即使还剩下几行



我正在尝试使用Paramiko (Python SSH库)读取远程文件,并遍历这些行。

我的文件看起来像这样:

# Instance Name      VERSION               COMMENT
Bob                  1.5                   Bob the Builder
Sam                  1.7                   Play it again, Sam

我的Paramiko代码看起来像这样:

def get_instances_cfg(self):
    '''
    Gets a file handler to the remote instances.cfg file.
    '''
    transport = paramiko.Transport(('10.180.10.104', 22))
    client = paramiko.SSHClient()
    #client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('some_host', username='victorhooi', password='password')
    sftp = client.open_sftp()
    fileObject = sftp.file('/tmp/instances.cfg','r')
    return fileObject
def get_root_directory(self):
    '''
    Reads the global instances.cfg file, and returns the instance directory.
    '''
    self.logger.info('Getting root directory')
    instances_cfg = self.get_instances_cfg()
    first_line = instances_cfg.next() # We skip the header row.
    instances = {}
    for row in instances_cfg:
        name, version, comment = row.split(None, 2)
        aeg_instances[name] = {
            'version': version,
            'comment': comment,
        }

由于某种原因,当我运行上面的代码时,当我在SFTP文件处理程序上运行.next()时,我得到了一个StopIteration错误:

first_line = instances_cfg.next() # We skip the header row.
File "/home/hooivic/python2/lib/python2.7/site-packages/paramiko/file.py", line 108, in next
raise StopIteration
StopIteration

这很奇怪,因为我正在读取的实例文本文件中有三行-我使用.next()来跳过标题行。

当我在本地打开文件时,使用Python的open(), .next()工作正常。

同样,我可以遍历SFTP文件处理程序,它将打印所有三行。

和使用。readline()而不是。next()似乎工作得很好,以及-不知道为什么。next()不是玩得很好。

这是Paramiko的SFTP文件处理程序的一些怪癖,还是我在上面的代码中遗漏了一些东西?

欢呼,维克多

next()函数只是在内部调用readline()唯一可以导致StopIteration是如果readline返回一个空字符串(查看代码,它是4行)。

查看readline()对文件的返回值。如果它返回一个空字符串,那么paramiko使用的行缓冲算法一定有问题。

最新更新