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.1
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 = '[email protected]'
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
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…