首页 > 解决方案 > 子进程输出中未正确显示 Unicode 字符

问题描述

我正在为 i3blocks 编写一个 python 脚本以在 Spotify 上显示当前的艺术家和歌曲,并subprocess.run()与 playerctl 一起使用来获取歌曲数据。输出没有正确显示日文字符,而是显示这样的文本\xe9\xa3\x9b\xe3\x81\xb9。换行符也显示为\n而不是实际的换行符。

我试过使用 string.decode("utf-8") ,得到了 error 'str' object has no attribute 'decode',我在解码之前尝试了string.encode("utf-8")and string.encode("ascii"),但输出与没有string.decode().

output = str(subprocess.run(["playerctl", "metadata"], capture_output = True))
lines = output.split("\\n")
artist = lines[5].split("artist")[1].strip()
title = lines[8].split("title")[1].strip()
print(artist, title)

正确的输出应该是tricot 飛べ,但实际输出是tricot \xe9\xa3\x9b\xe3\x81\xb9

标签: pythonpython-3.xlinuxsubprocess

解决方案


这部作品

t = b"tricot \xe9\xa3\x9b\xe3\x81\xb9"
t.decode("utf-8")

因为您的字符串必须是 - 执行解码方法的二进制字符串


推荐阅读