execjs执行js编码错误的解决方法(UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xad in position 20: illegal )

源码:

with open('test.js','r',encoding='utf-8') as f:
    js_text=f.read()
    # print(js_text)
    compil=execjs.compile(js_text)
    cookie=compil.call('sdk_1')
print(cookie)

报错:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "c:\users\administrator\appdata\local\programs\python\python38\lib\threading.py", line 932, in _bootstrap_inner
    self.run()
  File "c:\users\administrator\appdata\local\programs\python\python38\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "c:\users\administrator\appdata\local\programs\python\python38\lib\subprocess.py", line 1370, in _readerthread
    buffer.append(fh.read())
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 20: illegal multibyte sequence
Traceback (most recent call last):
  File "D:/niu/shiji/shiji/spiders/test.py", line 241, in <module>
    cookie=compil.call('sdk_1')
  File "C:\Users\Administrator\Envs\tengfang\lib\site-packages\execjs\_abstract_runtime_context.py", line 37, in call
    return self._call(name, *args)
  File "C:\Users\Administrator\Envs\tengfang\lib\site-packages\execjs\_external_runtime.py", line 92, in _call
    return self._eval("{identifier}.apply(this, {args})".format(identifier=identifier, args=args))
  File "C:\Users\Administrator\Envs\tengfang\lib\site-packages\execjs\_external_runtime.py", line 78, in _eval
    return self.exec_(code)
  File "C:\Users\Administrator\Envs\tengfang\lib\site-packages\execjs\_abstract_runtime_context.py", line 18, in exec_
    return self._exec_(source)
  File "C:\Users\Administrator\Envs\tengfang\lib\site-packages\execjs\_external_runtime.py", line 87, in _exec_
    output = self._exec_with_pipe(source)
  File "C:\Users\Administrator\Envs\tengfang\lib\site-packages\execjs\_external_runtime.py", line 103, in _exec_with_pipe
    stdoutdata, stderrdata = p.communicate(input=input)
  File "c:\users\administrator\appdata\local\programs\python\python38\lib\subprocess.py", line 1028, in communicate
    stdout, stderr = self._communicate(input, endtime, timeout)
  File "c:\users\administrator\appdata\local\programs\python\python38\lib\subprocess.py", line 1420, in _communicate
    stdout = stdout[0]
IndexError: list index out of range

Process finished with exit code 1

错误出在python内部的subprocess.py文件

解决方式:

第一种:打开subprocess.py文件,找到初始化函数__init__(),修改参数的默认值为encoding=‘utf-8’,程序运行不再报错
第二种:

import subprocess
from functools import partial

subprocess.Popen = partial(subprocess.Popen, encoding="utf-8")

这三句话,在导入 execjs之前写进去

上一篇:【新手上路】LeetCode刷题之“杨辉三角”


下一篇:在Flutter项目使用FFI调用Golang项目全记录