2011-11-15 4 views
0

Paramiko(Python SSHライブラリ)を使用してリモートファイルを読み込み、その行を繰り返し処理しようとしています。Parmiko SFTP File - 行が残っていても.next()を呼び出すと、直ちにStopIterationが発生します。

私のファイルは、このようなものになります。私は、上記を実行するととき、私、私はStopIterationエラーを取得し、いくつかの理由

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

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

マイParamikoコードは次のようになります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 

これは、私が読んでいるインスタンスのテキストファイルには3行あります。ヘッダー行をスキップするには.next()を使用しています。

ファイルをローカルで開くと、Pythonのopen()、.next()を使用して正常に動作します。

また、私はSFTPファイルハンドラをうまく反復することができ、3行すべてを出力します。

.next()の代わりに.readline()を使用すると、正常に動作するようにも見えます。なぜ.next()がうまく動作しないのかわかりません。

これはParamikoのSFTPファイルハンドラのいくつかの変わったものですか、または上記のコードで何か不足していますか?

乾杯、 ビクター

答えて

0

next()機能は、単に内部readline()を呼んでいます。 StopIterationの原因となるものは、readlineが空の文字列を返した場合です(コードを見ると4行です)。

readline()の返品があなたのファイル用であることを見てください。空文字列を返す場合は、paramikoが使用する行バッファリングアルゴリズムにバグが存在する必要があります。

関連する問題