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之前写进去

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿肆si

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值