【问题标题】:DecodeError in Paramiko Remote FileParamiko 远程文件中的解码错误
【发布时间】:2014-11-20 18:26:50
【问题描述】:

我有一个每天自动生成的大型远程文件。我无法控制文件的生成方式。我正在使用 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 的范围。

有没有办法在读取时重新编码该行或简单地忽略错误?

【问题讨论】:

    标签: python ssh paramiko


    【解决方案1】:

    所以,文件是字节。它们可能有也可能没有某些特定的编码。此外,paramiko is always returning bytes,因为它忽略了普通 open 函数采用的 'b' 标志。

    相反,您应该尝试自己解码每一行。首先,以二进制模式打开文件,然后读取一行,然后尝试将该行解码为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。

    【讨论】:

      猜你喜欢
      • 2011-06-22
      • 2017-08-20
      • 2016-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-08
      • 2016-08-24
      相关资源
      最近更新 更多