How can I execute JavaScript code from Python?

后端 未结 1 1171
野性不改
野性不改 2020-12-25 09:43

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(         


        
相关标签:
1条回答
  • 2020-12-25 10:19

    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)
    

    For your particular case, with file.js as

    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.

    0 讨论(0)
提交回复
热议问题