首页 > 解决方案 > Python3 .replace 产生 TypeError:需要一个类似字节的对象,而不是“str”

问题描述

我一直在尝试使用以下代码从服务器读取输出:

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()" 行时,会抛出“TypeError: a bytes-like object is required, not 'str'”。

我究竟做错了什么?

标签: pythonpython-3.x

解决方案


您必须解码字节对象以获取字符串。去做这个:

output = stdout.read().decode("UTF-8")

在那里用远程机器的编码替换 UTF-8。


推荐阅读