From 92657547878141aae630951b66bd1ef48ae03379 Mon Sep 17 00:00:00 2001 From: curder Date: Fri, 16 Aug 2024 14:21:11 +0800 Subject: [PATCH] Add code snippet --- docs/.vitepress/config.ts | 6 ++++ .../python/python-executes-js-code.md | 29 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 docs/programming-language/python/python-executes-js-code.md diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 446f38b..a397f6d 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -66,6 +66,12 @@ function sidebarProgrammingLanguage() {text: "使用 docker 编译静态资源", link: "/programming-language/node/compile-static-resources-using-docker"}, ], }, + { + text: "Python", + items: [ + {text: 'Python 执行 JS 代码', link: "/programming-language/python/python-executes-js-code"}, + ] + }, { text: "Others", items: [ diff --git a/docs/programming-language/python/python-executes-js-code.md b/docs/programming-language/python/python-executes-js-code.md new file mode 100644 index 0000000..74c8ea3 --- /dev/null +++ b/docs/programming-language/python/python-executes-js-code.md @@ -0,0 +1,29 @@ +# Python 执行 JS 代码 + +[`PyExecJS`](https://pypi.org/project/PyExecJS/) 是一个Python库,用于在Python中执行JavaScript代码。 + +## 安装 + +```bash +pip install PyExecJS +``` + +## 示例代码 + +```python +import execjs + +# 定义JavaScript代码 +js_code = """ + function hello(name) { + return `Hello ${name}!`; + } + """ + +# 编译JavaScript代码 +context = execjs.compile(js_code) + +# 调用JavaScript函数 +result = context.call('hello', 'Python') +print(result) # 输出:Hello Python! +``` \ No newline at end of file