【问题标题】:Python3 .replace yielding TypeError: a bytes-like object is required, not 'str'Python3 .replace 产生 TypeError:需要一个类似字节的对象,而不是“str”
【发布时间】:2020-10-17 15:28:12
【问题描述】:

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

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'" 被抛出。

我做错了什么?

【问题讨论】:

  • output 似乎是一串字节;您需要在应用 replace 之前将其解码为(字符)字符串 - 类似于 output.decode('utf-8').replace("\n", ",").strip(),调整为特定编码。

标签: python python-3.x


【解决方案1】:

你必须解码字节对象来获取字符串。为此:

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

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

【讨论】:

    【解决方案2】:

    outputbytes 对象,而不是 str。您还需要传递其replace 方法bytes,在这种情况下,通过在文字中添加b 前缀:

    x = output.replace(b"\n", b",").strip()
    

    【讨论】:

      猜你喜欢
      • 2017-08-18
      • 1970-01-01
      • 2016-01-05
      相关资源
      最近更新 更多