Skip to main content
 首页 » 编程设计

python之Paramiko 远程文件中的解码错误

2025年05月04日8zhujiabin

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

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

请您参考如下方法:

所以,文件是字节。它们可能有也可能没有一些特定的编码。此外,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。