如何从Python执行JavaScript代码?

时间:2020-12-31 21:05:51

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

可以说我在JavaScript文件中有这个代码:

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

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:

我如何使用Python执行此代码并“打印”x和Hello World!?这是一些伪代码,进一步解释了我的想法:

# 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!"

1 个解决方案

#1


9  

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

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

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)

For your particular case, with file.js as

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

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

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

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

#1


9  

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

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

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)

For your particular case, with file.js as

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

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

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

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