python 运行 execjs 出现错误 UnicodeEncodeError: 'gbk' codec can't encode character '\xfe' in positio

发布时间 2023-08-16 20:50:45作者: 守护式等待

异常解读

该异常的格式一般为:

UnicodeEncodeError: 'gbk' codec can't encode character '\xfe' in positio

该异常出现的场景为在 Windows 电脑下使用 Python execjs 运行指定的 JS 文件,但 JS 文件中包含中文。

异常解决方案

该问题解决需要 修改 你电脑 Python 安装目录下 lib 文件夹里面的一个文件,名字叫做 subprocess.py

例如在我本地为 :

 通过任意文本编辑器打开该文件,在文件中检索 encoding,找到如下位置:

修改 encoding=None 为 encoding = "utf-8" 。

    def __init__(self, args, bufsize=-1, executable=None,
                 stdin=None, stdout=None, stderr=None,
                 preexec_fn=None, close_fds=True,
                 shell=False, cwd=None, env=None, universal_newlines=None,
                 startupinfo=None, creationflags=0,
                 restore_signals=True, start_new_session=False,
                 pass_fds=(), *, encoding="utf-8", errors=None, text=None):
        """Create new Popen instance."""
        _cleanup()
        # Held while anything is calling waitpid before returncode has been
        # updated to prevent clobbering returncode if wait() or poll() are
        # called from multiple threads at once.  After acquiring the lock,
        # code must re-check self.returncode to see if another thread just
        # finished a waitpid() call.
        self._waitpid_lock = threading.Lock()

保存文件,解决问题。