Python3.replace产生TypeError:需要类似字节的对象,而不是';str';
我一直在尝试使用以下代码读取服务器的输出:Python3.replace产生TypeError:需要类似字节的对象,而不是';str';,python,python-3.x,Python,Python 3.x,我一直在尝试使用以下代码读取服务器的输出: s = paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname, port, username, password) command = 'xe vm-list' (stdin, stdout, stderr) = s.exec_command(command) o
s = paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
s.connect(hostname, port, username, password)
command = 'xe vm-list'
(stdin, stdout, stderr) = s.exec_command(command)
output = stdout.read()
x = output.replace("\n", ",").strip()
print(x)
s.close()
当运行行“x=output.replace(“\n”,“,”).strip()”时,“类型错误:需要类似字节的对象,而不是“str”)
我做错了什么?
输出
是一个字节
对象,而不是str
。您还需要传递其replace
方法bytes
,在这种情况下,您可以向文本添加b
前缀:
x = output.replace(b"\n", b",").strip()
您必须解码bytes对象才能获得字符串。为此:
output = stdout.read().decode("UTF-8")
在那里,用远程机器的编码替换UTF-8。
输出似乎是一个字节字符串;在应用replace
-类似于output.decode('utf-8')。replace(“\n”,“,”)。strip()
,调整为特定编码之前,您需要将其解码为(字符)字符串。