简体   繁体   English

如何从 Python 执行 JavaScript 代码?

[英]How can I execute JavaScript code from Python?

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!我将如何使用 Python 执行此代码并“打印” xHello 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!"

The module Naked does exactly this. Naked模块正是这样做的。 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' ,您可以根据需要对其进行解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM