Node.js调用Python子进程时string.decode()报错如何解决
Python 被 Node.js child_process 调用时 UTF-8 字符打印报错解决方案
问题现象
Python 脚本解码 UTF-8 字符串的逻辑,直接在系统控制台、Python 解释器中运行均正常,但通过 Node.js 的 child_process 模块调用时触发编码报错。
报错信息
Traceback (most recent call last): File "test.py", line 1, in <module> print(b'\xe1\x83\x90'.decode("utf-8")) File "C:\Program Files\Python38\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u10d0' in position 0: character maps to <undefined>
原始代码
Node.js 侧代码(index.js)
const spawn = require("child_process").spawn; const python = spawn("python", ["test.py"]); python.stdout.pipe(process.stdout); python.stderr.pipe(process.stdout)
初始 Python 侧代码(test.py)
print(b'\xe1\x83\x90'.decode("utf-8"))
问题根因
通过 Node.js child_process spawn 启动 Python 子进程时,Python 进程的 stdout 输出流默认编码会被设置为 cp1252(Windows 环境常见单字节编码),该编码无法兼容所有 UTF-8 字符。解码后的 Unicode 字符在打印输出时,需要先按照 stdout 的编码转为字节流,cp1252 编码无法映射目标 UTF-8 字符,就会触发上述报错。
你可以执行print(sys.stdout.encoding)查看当前 Python 进程的 stdout 编码,验证编码配置是否符合预期。
解决方案
修改 Python 代码,显式将 stdout 输出流的编码重新配置为 UTF-8 即可解决问题:
import sys sys.stdout.reconfigure(encoding='utf-8') print(b'\xe1\x83\x90'.decode())
内容的提问来源于stack exchange,提问作者datoad
相关产品推荐
相关产品推荐

