美文网首页
Windows (win10) 执行Python脚本,输入文件失

Windows (win10) 执行Python脚本,输入文件失

作者: 偷油考拉 | 来源:发表于2021-08-16 11:00 被阅读0次

报错提示:
UnicodeEncodeError: 'gbk' codec can't encode character '\xa0' in position 0: illegal multibyte sequence

问题分析

因为windows默认使用gbk作为默认字符编码格式,所以python以utf8写入失败。
这里强制python打开windows文件的时候,以utf8格式。

解决方案:

  1. 方法1
    设置环境变量PYTHONIOENCODING
C:\> set PYTHONIOENCODING=utf8
C:\> test.py > out.txt
  1. 方法2
    设置环境变量 PYTHONUTF8
set PYTHONUTF8=1
  1. 方法3
    在python命令行加入-X参数指定utf8
python -Xutf8 test.py > 3.txt

参考资料

Error occurs when trying to redirect Python UTF-8 stdout to a file on Windows - Stack Overflow

Python: Use the UTF-8 mode on Windows! - DEV Community

1. Command line and environment — Python 3.9.6 documentation

相关文章

网友评论

      本文标题:Windows (win10) 执行Python脚本,输入文件失

      本文链接:https://www.haomeiwen.com/subject/fgdmbltx.html