python在 调用execjs库  执行js时 ,会报编码错误,这里提供了两种解决方案

异常输出示例

Traceback (most recent call last):
  File "C:\Users\shentianxun\Desktop\yrxy\比赛\1\1.py", line 47, in <module>
    print(execjs.compile(js_code).call('main', 1))
  File "D:\python\lib\site-packages\execjs\_abstract_runtime_context.py", line 37, in call
    return self._call(name, *args)
  File "D:\python\lib\site-packages\execjs\_external_runtime.py", line 92, in _call
    return self._eval("{identifier}.apply(this, {args})".format(identifier=identifier, args=args))
  File "D:\python\lib\site-packages\execjs\_external_runtime.py", line 78, in _eval
    return self.exec_(code)
  File "D:\python\lib\site-packages\execjs\_abstract_runtime_context.py", line 18, in exec_
    return self._exec_(source)
  File "D:\python\lib\site-packages\execjs\_external_runtime.py", line 87, in _exec_
    output = self._exec_with_pipe(source)
  File "D:\python\lib\site-packages\execjs\_external_runtime.py", line 103, in _exec_with_pipe
    stdoutdata, stderrdata = p.communicate(input=input)
  File "D:\python\lib\subprocess.py", line 964, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "D:\python\lib\subprocess.py", line 1290, in _communicate
    self._stdin_write(input)
  File "D:\python\lib\subprocess.py", line 898, in _stdin_write
    self.stdin.write(input)
UnicodeEncodeError: 'gbk' codec can't encode character '\xae' in position 220: illegal multibyte sequence

 

 

 

 

方案1

 比较简单,但是每次使用 都要加

import subprocess
from functools import partial
subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")
# 修改编码方式,window默认编码是gbk,Mac和Linux 默认是uft-8
 
#先修改编码方式 然后导入 execjs import execjs

 

 

 

方案2

一点点麻烦,但是一劳永逸

 

1.通过点击异常消息  进入subprocess.py文件

 

 

2.在subprocess.py文件 中 搜索  encoding=  找到指定位置

 

 

 

3.把原本的 None 改成  'utf-8'

 

 posted on 2023-02-22 17:30  宁青楼  阅读(3233)  评论(0)    收藏  举报