我很难将subprocess.run
函数与一个包含重音字符(例如"é")的命令一起使用.
考虑这个简单的例子:
# -*- coding: utf-8 -*-
import subprocess
cmd = "echo é"
result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
print("Output of subprocess.run : {}".format(result.stdout.hex()))
print("é char encoded manually : {}".format("é".encode("utf-8").hex()))
它提供以下输出:
Output of subprocess.run : 820d0a
é char encoded manually : c3a9
我不明白subprocess.run
的返回值,难道不应该也是c3a9
吗?我知道0d0a
是CR+LF,但为什么是82
?
正因为如此,当我try 运行这条线路时:
output = result.stdout.decode("utf-8")
我收到UnicodeDecodeError异常,并显示以下消息:'utf-8' codec can't decode byte 0x82 in position 0: invalid start byte
我try 以如下方式显式指定编码格式:
result = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, encoding="utf-8")
但这在调用subprocess.run
时会引发相同的异常('utf-8' codec can't decode byte 0x82 in position 0: invalid start byte
).
我在装有Python3.8.5的Windows10上运行这个程序.
我希望有人能帮我这个忙,有什么提示吗?