Parmiko SFTP文件 - 调用.next()立即引发StopIteration,尽管还有剩余行

0 投票
1 回答
894 浏览
提问于 2025-04-17 06:19

我正在尝试使用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文件处理器的某种怪癖,还是我在上面的代码中遗漏了什么?

谢谢,
Victor

1 个回答

0

next()这个函数其实就是在内部调用了readline()。导致StopIteration的唯一原因就是readline()返回了一个空字符串(看看代码,只有4行)。

你可以检查一下readline()对你的文件返回的是什么。如果返回的是空字符串,那就说明paramiko使用的行缓冲算法可能有问题。

撰写回答