Skip to content Skip to sidebar Skip to footer

Trying To Run Javascript From Python

I am trying to run the below script from Python. import execjs var request = require('request'); var apiHostName='https:/url.com'; emailAddress = 'my.email@company.com' apiKey =

Solution 1:

First, you're using a library, PyExecJS, which claims to be both no longer maintained, and poorly designed.

So, this probably isn't the best choice in the first place.


Second, you're using it wrong.

The examples all include JS code as strings, which are passed to execjs.eval or execjs.compile.

You're trying to include JS code directly inline as if it were Python code. That isn't going to work; it will try to parse the JS code as Python and raise a SyntaxError because they aren't the same language.

So, you have to do the same thing as the examples. That might look something like this:

import execjs

jscode = """
    var request = require('request');

    var apiHostName='https:/url.com';

    emailAddress = 'my.email@company.com'
    apiKey = 'api_key'

    function callback(error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Identity with email address " + emailAddress + " found:");
        var b= JSON.parse(body);
        console.log("id="+b.identityId+",api key="+b.apiKey+",type="+b.type);
      } else{
        if (response.statusCode == 401) {
          console.log ("Couldn't recognize api key="+apiKey);
        } else if (response.statusCode == 403) {
          console.log ("Operation forbidden for api key="+apiKey);
        } else if (response.statusCode == 404) {
          console.log ("Email address " +emailAddress + " not found");
        }
      }
    }
"""
execjs.eval(jscode)

Or, probably even better, move the JavaScript to a separate .js file, then run it like this:

import os.path
import execjs

dir = os.path.dirname(__file__)
with open(os.path.join(dir, 'myscript.js')) as f:
    jscode = f.read()
execjs.eval(jscode)

1. Someone could write an import hook for Python that did something similar to perl's Inline::Python, Inline::Java, etc. for Python, allowing you to embed code from other languages directly in your Python scripts. Periodically, someone does try to write such a thing, but they always seem to abandon it as a bad idea before it's even production-ready, or redesign it to be more like PyExecJS.


Post a Comment for "Trying To Run Javascript From Python"