有时候,一些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