Paramiko远程文件中的DecodeError

时间:2014-11-20 18:26:51

标签: python ssh paramiko

我有一个每天自动生成的大型远程文件。我无法控制文件的生成方式。我正在使用Paramiko打开文件然后搜索它以查找给定的行是否与文件中的行匹配。

但是,我收到以下错误:

UnicodeDecodeError:'utf8'编解码器无法解码位置57中的字节0x96:无效的起始字节

我的代码:

self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(host, username=user, password=pass)

self.sftp_client = self.ssh.open_sftp()
self.remote_file = self.sftp_client.open(filepath, mode='r')

def checkPhrase(self, phrase):
    found = 0
    self.remote_file.seek(0)
    for line in self.remote_file:
        if phrase in line:
            found = 1
            break
    return found

我收到了错误:for line in self.remote_file:显然文件中的字符超出了utf8的范围。

有没有办法在读取行时重新编码行,或者只是忽略错误?

1 个答案:

答案 0 :(得分:-1)

所以,文件是字节。它们可能有也可能没有某种特定的编码。此外,paramiko is always returning bytes,因为它忽略了正常'b'函数所需的open标记。

相反,您应该尝试自己解码每一行。首先,以二进制模式打开文件,然后读取一行,然后尝试将该行解码为utf-8。如果失败,只需跳过该行。

def checkPhrase(self, phrase):
    self.remote_file.seek(0)
    for line in self.remote_file:
        try:
            decoded_line = line.decode('utf-8')  # Decode from bytes to utf-8
        except UnicodeDecodeError:
            continue  # just keep processing other lines in the file, since this one it's utf-8

        if phrase in decoded_line:
            return True  # We found the phrase, so just return a True (instead of 1)
    return False  # We never found the phrase, so return False (instead of 0)

此外,我发现Ned Batcheldar的Unipain pycon talk对于理解字节与unicode非常有帮助。