如何从Python执行JavaScript代码? [英] How can I execute JavaScript code from Python?

查看:128
本文介绍了如何从Python执行JavaScript代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在JavaScript文件中包含此代码:

Lets say that I have this code inside a JavaScript file:

var x = 10;
x = 10 - 5;
console.log(x);
function greet() {
  console.log("Hello World!");
}
greet()

我如何使用Python执行此代码和打印 x Hello World!

这是一些伪代码,进一步解释了我的想法:

How would I use Python to execute this code and "print" x and Hello World!?
Here is some pseudo code that further explains what I'm thinking:

# 1. open the script
script = open("/path/to/js/files.js", "r")
# 2. get the script content
script_content = script.read()
# 3. close the script file
script.close()
# 4. execute the script content and "print" "x" and "Hello World!"
x = js.exec(script_content)

并且,预期结果如下所示:

And, the expected result would look like this:

>>> 5
>>> "Hello World!"


推荐答案

模块 Naked 正是这样做的。 pip install Naked (或者如果您愿意,可以从源代码安装)并导入库shell函数,如下所示:

The module Naked does exactly this. pip install Naked (or install from source if you prefer) and import the library shell functions as follows:

from Naked.toolshed.shell import execute_js, muterun_js

response = muterun_js('file.js')
if response.exitcode == 0:
  print(response.stdout)
else:
  sys.stderr.write(response.stderr)

对于您的特定情况,将file.js作为

For your particular case, with file.js as

var x = 10;
x = 10 - 5;
console.log(x);
function greet() {
      console.log("Hello World!");
}
greet()

输出 '5 \\\
Hello World!\ n'
,您可以根据需要进行解析。

the output is '5\nHello World!\n', which you can parse as desired.

这篇关于如何从Python执行JavaScript代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆