在window系统中,python通过subprocess模块调用shell执行cmd命令。
我们知道在中文的window系统中系统默认编码是gb2312,而python默认编码是utf8,也就意味着我们的cmd命令字符串是utf8编码格式的,使用utf8编码格式的送入gb2312编码格式的shell导致编码混乱,执行肯定会报错的(英文不会报错,因为utf8和gb2312都兼容asci编码)。所以为了能够正确执行含有中文的命令,需要两步:一是获取shell默认编码,而是对要执行的字符串进行编码。
(1)获取shell的编码:
import locale
print(locale.getdefaultlocale())
(2)将cmd转化为shell中正确的编码
import locale
cmd = cmd.encode(locale.getdefaultlocale()[1])
subprocess.Popen(cmd)