How can I execute JavaScript code from Python?

Let's 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() 

How can I use Python to execute this code and "print" x and Hello World! ?
Here is some kind of pseudo code that further explains what I think:

 # 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 will look like this:

 >>> 5 >>> "Hello World!" 
+6
source share
1 answer

The Naked module does just that. pip install Naked (or install from the source if you want) 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) 

In your specific case with the .js file as

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

the output of '5\nHello World!\n' , which you can analyze as you wish.

+6
source

All Articles