python 使用node_vm2执行js

有时候,一些js需要调用,之前都是用nodejs比较多,但是有些js会验证是否使用的是node
就比如某头条的加密。为了能本地调用扣下来的js,这里就不能用nodejs或者execjs,
需要用到vm2

步骤:
1、下载vm2

pip install node_vm2 -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

加载方式如下:

大多数 API 都绑定到vm2。

简单评估:

from node_vm2 import eval

print(eval("['foo', 'bar'].join()"))

使用虚拟机:

from node_vm2 import VM

with VM() as vm:
   vm.run("""
      var sum = 0, i;
      for (i = 0; i < 10; i++) sum += i;
   """)
   print(vm.run("sum"))

使用 NodeVM:

from node_vm2 import NodeVM

js = """exports.greet = name => console.log(`Hello ${name}!`);"""

with NodeVM.code(js) as module:
   module.call_member("greet", "John")

可以使用 Promise 执行异步任务:

from datetime import datetime
from node_vm2 import NodeVM

js = """
exports.test = () => {
   return new Promise(resolve => {
      setTimeout(() => {
         resolve("hello")
      }, 3000);
   });
};
"""
with NodeVM.code(js) as module:
   print(datetime.now())
   print(module.call_member("test"))
   print(datetime.now())

如果您希望允许 VM 使您的服务器崩溃(例如process.exit()),您应该在单独的服务器中创建 VM,这样它就不会影响其他 VM:

from node_vm2 import VMServer, VM

with VMServer() as server:
   with VM(server=server) as vm:
      # now the vm is created in a new server
      print(vm.run("1 + 2 + 3"))

使用上面的代码如果出现如下报错,直接进入报错文件

self.process.stdin.write(text.encode("utf-8")) TypeError: write() argument must be str, not bytes

修改两个地方,即可解决问题(删除编码解码就可以了)

对应文件

C:\Users\Administrator.DESKTOP-2H1B0HM\AppData\Local\Programs\Python\Python37\Lib\site-packages\node_vm2\__init__.py

第一个

with self.write_lock:
		self.process.stdin.write(text.encode("utf-8"))
#这里的内容改成
with self.write_lock:
		self.process.stdin.write(text)

第二个

try:
	# FIXME: https://github.com/PyCQA/pylint/issues/922
	data = json.loads(data.decode("utf-8")) or {}
except json.JSONDecodeError:
#改成
try:
	# FIXME: https://github.com/PyCQA/pylint/issues/922
	data = json.loads(data) or {}
except json.JSONDecodeError:

API 参考

http://node-vm2.readthedocs.io/

项目地址:https://github.com/eight04/node_vm2

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

火浴R

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

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

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

打赏作者

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

抵扣说明:

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

余额充值