Python3调用Windows工具diskpart时变音符号显示异常求助
解决Python调用diskpart时变音符号显示乱码的问题
问题根源
Windows自带的diskpart工具输出采用系统OEM编码(一般是GBK,具体取决于系统语言),而Python的subprocess.Popen启用text=True时,默认会用utf-8编码解码输出,编码不匹配直接导致变音符号乱码。命令行里运行正常,是因为命令行自动适配了系统的编码规则。
解决方案
不要依赖text=True的自动编码处理,手动指定diskpart对应的编码即可。
方法1:直接指定编码
通过encoding参数设置为系统的OEM编码,用locale.getpreferredencoding(False)就能获取到这个编码:
import subprocess import locale # 获取系统OEM编码 oem_encoding = locale.getpreferredencoding(False) try: proc = subprocess.Popen( ['diskpart'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, encoding=oem_encoding # 指定正确编码 ) stdout, stderr = proc.communicate(input=diskpart_command) if proc.returncode == 0: logger.info(f"Diskpart command executed successfully: {diskpart_command}") return stdout else: error_message = f"Error executing diskpart: {stderr}" logger.error(error_message) return error_message except Exception as e: logger.error(f"Exception occurred: {str(e)}") return str(e)
方法2:字节流手动解码
如果担心自动编码出问题,也可以先读取字节流,再手动用系统OEM编码解码:
import subprocess import locale oem_encoding = locale.getpreferredencoding(False) try: proc = subprocess.Popen( ['diskpart'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=False # 关闭自动文本模式,读取原始字节 ) # 输入命令也要用对应编码转成字节 stdout_bytes, stderr_bytes = proc.communicate(input=diskpart_command.encode(oem_encoding)) # 解码字节流为文本 stdout = stdout_bytes.decode(oem_encoding) stderr = stderr_bytes.decode(oem_encoding) if proc.returncode == 0: logger.info(f"Diskpart command executed successfully: {diskpart_command}") return stdout else: error_message = f"Error executing diskpart: {stderr}" logger.error(error_message) return error_message except Exception as e: logger.error(f"Exception occurred: {str(e)}") return str(e)
验证建议
测试时可以找个带变音符号的磁盘(比如名称包含ä、ö、ü这类字符)运行命令,确认输出是否正常显示。
内容的提问来源于stack exchange,提问作者MrSicko
相关产品推荐
相关产品推荐

