SoFunction
Updated on 2025-03-04

Summary of several methods for calling JavaScript code in Python

1. Execute JavaScript code using PyExecJS

PyExecJSis a popular Python library that can be used to run JavaScript code in Python. Through this library, Python code can call JS functions and return results.

Install PyExecJS

pip install PyExecJS

Example of usage

import execjs

# Create an execution contextctx = ("""
    function add(a, b) {
        return a + b;
    }
""")

# Call functions in JavaScriptresult = ("add", 3, 5)
print(result)  # Output 8

2. Execute JavaScript using node-vm module

node-vmis a virtual machine module provided, which allows us to create a sandbox environment to run code in JavaScript. Called via Pythonnode-vm, JavaScript code can be executed in a constrained environment and the result can be returned. This approach is especially suitable for scenarios where JavaScript code needs to be executed in an isolated environment.

Install PyNode

pip install node_vm2

Example of usage

from node_vm2 import VM

with VM() as vm:
   ("""
      function add(a, b){
          return a + b;
      }
      
      let sum = add(3, 5);
   """)
   print(("sum"))

3. Use selenium to control the browser to execute JavaScript

In some cases, you may need to simulate a browser environment to execute JavaScript.seleniumIt is a powerful web automation tool that can be used to start a browser, execute JavaScript, and get the content of the browser page.

Install selenium

pip install selenium

Example of usage

from selenium import webdriver

# Start the browserdriver = ()

# Load the web page("")

# Execute JS coderesult = driver.execute_script("return 3 + 5;")
print(result)  # Output 8
# Close the browser()

4. Use subprocess to execute scripts

If you have a standalone JavaScript file and want to call it through Python, you can usesubprocessModule to start a process, execute the script and get the results.

Example: Execute scripts through subprocess

import subprocess

# Define scriptjs_code = """
function add(a, b){
    return a + b;
}
(add(1, 2));
"""

# Create script filewith open('', 'w') as f:
    (js_code)

# Execute scriptprocess = (['node', ''], stdout=)

# Get the output resultoutput, error = ()

# Print the output of a JS scriptprint(())  # Output 3

Summarize

Through the above methods, Python developers can flexibly call JavaScript code in different scenarios. I hope this article can provide you with some useful references to help you better realize the collaboration between Python and JavaScript!

This is the end of this article about several methods of calling JavaScript code in Python. For more related contents of Python calling JavaScript code, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!