我正在连接一台使用paramiko并提取其syslog的机器。当我试图使用函数readline()时,我得到了UnicodeDecodeError。
这是一个节目:
print_all_lines="awk 'FNR>=%s && FNR <=%s' /var/log/syslog" %(line_number_start, line_number_end)
stdin, stdout, stderr = SSH.exec_command(print_all_lines)
stdout.readlines()这是一个错误:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc5 in position 199: invalid continuation byte发布于 2017-07-11 10:27:22
readline()和readlines()将尝试将数据解码为UTF-8,因此如果数据不在UTF-8中,则可能会失败。您可以只使用不执行解码的read():
stdin, stdout, stderr = SSH.exec_command(print_all_lines)
s = stdout.read()参见下面的示例(在交互式python中):
>>> stdin, stdout, stderr = ssh.exec_command(r'printf \\xc5\\n')
>>> v = stdout.readlines()
Traceback (most recent call last):
[...snip...]
File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xc5 in position 0:
invalid continuation byte
>>>
>>> stdin, stdout, stderr = ssh.exec_command(r'printf \\xc5\\n')
>>> v = stdout.read()
>>> v
'\xc5\n'
>>>更新:
只看一下Paramiko的源代码,它有一个无文档的函数_set_mode(),它可以用来将stdout设置为二进制模式,从而禁用解码:
>>> stdin, stdout, stderr = ssh.exec_command(r'printf \\xc5\\n\\xc5\\n')
>>> stdout._set_mode('b')
>>> v = stdout.readlines()
>>> v
['\xc5\n', '\xc5\n']
>>>https://stackoverflow.com/questions/45028633
复制相似问题