2011-11-15 29 views
0

我試圖使用Paramiko(Python SSH庫)來讀取遠程文件,並遍歷行。Parmiko SFTP文件 - 調用.next()會立即導致StopIteration,即使有線仍然

我的文件看起來是這樣的:

# 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, 
     } 

出於某種原因,當我運行上面,我得到一個StopIteration錯誤,當我在SFTP文件處理程序上運行.next():

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 

這很奇怪,因爲我正在閱讀的實例textfile中有三行 - 我使用.next()跳過標題行。

當我在本地打開文件時,使用Python的open(),.next()工作正常。

此外,我可以遍歷SFTP文件處理程序罰款,它會打印所有三行。

而使用.readline()而不是.next()似乎也很好 - 不知道爲什麼.next()播放不好。

這是Paramiko的SFTP文件處理程序的一些怪癖,還是我錯過了上面的代碼中的東西?

乾杯, 維克多

回答

0

的的next()功能簡單地調用readline()內部。 只有可能導致StopIteration的事情是,如果readline返回一個空字符串(查看代碼,它是4行)。

看看readline()的回報是爲您的文件。如果它返回一個空字符串,則paramiko使用的行緩衝算法中必須存在一個錯誤。

相關問題