Python使用pyv8

# -*- coding: utf-8 -*-
# @Time : 2019-10-27 19:54
# @Author : cxa
# @File : hello_pyv8.py
# @Software: PyCharm


import PyV8
from pathlib import Path
import json


def read_file():
    js_data = ""
    file_path = Path.cwd() / "hello_pyv8.js"
    with file_path.open("r", encoding="utf-8") as fs:
        js_data = fs.read()
    return js_data


def func1():
    """
    调用的时候使用Python代码
    :return:
    """
    result1 = ""
    with PyV8.JSLocker() as lock:
        with PyV8.JSContext() as  ctxt:
            js = read_file()
            ctxt.eval(js)
            locals = ctxt.locals
            result1 = locals.a(9_0_0)  # 使用Python的形式
        print("result1", result1)


def func2():
    result2 = ""
    with PyV8.JSLocker() as lock:
        with PyV8.JSContext() as  ctxt:
            run_js = """
            a(123)
            """
            js = read_file() + run_js
            result2 = ctxt.eval(js)
        print("result2", result2)


def func3():
    with PyV8.JSContext() as  ctxt:
        js = read_file()
        ctxt.eval(js)
        js_locals = ctxt.locals
        dic = {"name": "张三", "age": 19}
        result3 = js_locals.get_name(dic)
        print(js_locals.navigator.userAgent)
        print("result3", result3)


def func4():
    result4 = None
    with PyV8.JSContext() as  ctxt:
        js = read_file()
        dic = """
        get_name({"name": "张三", "age": 19},"name")
        """

        result4 = ctxt.eval(js + dic)
        print("result4", result4)


if __name__ == '__main__':
    func1()
    print("---" * 30)
    func2()
    print("---" * 30)
    func3()
    print("---" * 30)
    func4()
    print("---" * 30)

posted @ 2019-10-27 20:39  公众号python学习开发  阅读(567)  评论(0编辑  收藏  举报