Polyglot programming is uncommon but can be a lifesaver in specific situations. For example, we recently wrote an article about executing Python scripts within a PHP/HTML file, which can be valuable for certain programmers.
Before we begin, ensure that Python with pip (also including Node.js would be better) is installed and properly configured on the system where you intend to carry out the practical tasks described in this article.
To begin, install PythonMonkey by executing the following command:
$ pip install pythonmonkey
After installation is complete, you can effortlessly import the library into your Python project and utilize the “
from pythonmonkey import eval as js_eval js_eval("console.log")('Hello from Linux TLDR')
For example, we have two files, “
math-script.js” and “
math-script.js” file will be called in the “
main.py” Python file.
Content of the “main.py“.
from pythonmonkey import require as js_require js_lib = js_require("./math-script") print(js_lib.add_func(1,6)) # 7 print(js_lib.sub_func(1,6)) # -5
Content of the “math-script.js“.
Now, when “
math-script.js” will be used to evaluate the assigned values, and the resulting output will be printed.
So, if you loved these libraries and want to continue your journey further, I suggest you check out a few basic to advanced examples from here.
PyExecJS was once quite popular, and the reason I mention this is that it’s now deprecated. However, I still use it in certain situations, and, of course, it can still handle basic tasks.
So, to begin, install the library using the Python package manager.
$ pip install PyExecJS
js_code” variable and executed using the “
compile()” and “
eval()” functions from the imported “
Now, since this library has reached its end of life (EOL), I won’t go further into a detailed explanation. However, if you’re interested in learning some hands-on techniques, feel free to check out its GitHub page.
To begin, type the following command in your terminal to install the js2py library:
$ pip install js2py
Now, we will explore a basic example of using this library in which a simple greeting message assigned to the “
js_code” variable will be printed.
import js2py js_code = """ console.log("Hello from Linux TLDR"); """ context = js2py.EvalJs() context.execute(js_code)
However, you can explore further by visiting this library’s GitHub page.
Now, you might be wondering which of the three libraries (excluding one that is deprecated) to choose for performing the same task. My answer would be: if you are unfamiliar and new to the topic, go for PythonMonkey without a doubt.
Till then, peace!