Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to Run JavaScript from Python ?

How to Run JavaScript from Python ?

In this article, we’ll discuss how to run a javascript file with Python. For this, we’ll use the JS2PY(Javascript Runtime in Pure Python) Python module. JS2PY works by translating JavaScript directly into Python. It indicates that you may run JS directly from Python code without installing large external engines like V8.

To use the module it first has to be installed into the system, since it is not built-in.

Syntax:

pip install js2py

To use the module it has to be imported.

Syntax:

import js2py

Now to convert javascript to python, the javascript command is stored as a string in some variable. We’ll now use the eval_js() function of the module js2py, and pass the javascript code to it.

eval_js() function is defined under the js2py module, which is used to evaluate javascript code, Pass the Javascript code as a parameter in the eval_js module.

Syntax:

js2py.eval_js(javascript code)

Example: Running a simple JS command in Python 

Python3




import js2py
  
code_2 = "function f(x) {return x+x;}"
res_2 = js2py.eval_js(code_2)
  
print(res_2(5))


Output: 

10

Now let us look at how a JS file is interpreted in Python. For this first *.js file is translated to *.py file

The js2py module provides one way for converting JS code to Python code we must use the translate_file() function for this. After the translation, we will import the Python file and provide something to the function declared within the javascript file.

translate_file() function accepts two arguments: a Javascript file and a Python file, finally it converts the Javascript file to a Python file.

Syntax:

js2py.translate_file(Javascript File, Python File)

Example:  Running a JS file using Python

Javascript File:

Javascript




function wish(name) {
    console.log("Hello, "+name+"!")
}


Python File: 

Python3




import js2py
from temp import *
  
js2py.translate_file("hey.js", "temp.py")
temp.wish("Lazyroar")


Output: 

Hello Lazyroar

We can also run JS without explicitly translating it. for this *.js is loaded into a variable through run_file() function.

run_file(): It is defined under the js2py module, which is used to run the Javascript file. It takes a Javascript file as an argument.

Syntax: 

js2py.run_file(Javascript File)

Example: Running JS in Python

Python3




import js2py
  
eval_res, tempfile = js2py.run_file("hey.js")
tempfile.wish("Lazyroar")


Output:

Hello Lazyroar

RELATED ARTICLES

Most Popular

Recent Comments