在 Windows 7 下使用 Python 2.7 尝试运行使用 utf-8 编码的 Windows 批处理文件时,无法识别批处理文件的第一个命令(参见示例)。
最有可能的是,bom 被解释为字符。如何让底层 shell 正确运行批处理文件?
调用的批处理文件来自第三方。这是一个重现问题的简单 python 脚本:
import codecs
import subprocess
content = "@echo off"
with codecs.open('test_utf8.bat', 'w', 'utf-8-sig') as f:
f.write(content)
f.close()
with open('test_ansi.bat', 'w') as f:
f.write(content)
f.close()
print "Calling test_ansi.bat"
subprocess.call('test_ansi.bat', shell=True)
print "Calling test_utf8.bat"
subprocess.call('test_utf8.bat', shell=True)
print "Done"
运行脚本会给出以下输出
t:\tmp\test>python test.py
Calling test_ansi.bat
Calling test_utf8.bat
t:\tmp\test>´╗┐@echo off
'´╗┐@echo' is not recognized as an internal or external command,
operable program or batch file.
Done
t:\tmp\test>
请注意,该shell
参数似乎没有任何效果。