Question

Thanks to python-spidermonkey, using JavaScript code from Python is really easy.

However, instead of using Python to read JS code from a file and passing the string to Spidermonkey, is there a way to read the file from within Spidermonkey (or pass the filepath as an argument, as in Rhino)?

Was it helpful?

Solution 2

Turns out you can just bind a Python function and use it from within Spidermonkey: http://davisp.lighthouseapp.com/projects/26898/tickets/23-support-for-file-io-js_evaluatescript

import spidermonkey

def loadfile(fname):
    return open(fname).read()

rt = spidermonkey.Runtime()
cx = rt.new_context()
cx.add_global("loadfile", loadfile)
ret = cx.execute('var contents = loadfile("foo.js"); eval(contents);')

OTHER TIPS

The SpiderMonkey as a library allows that by calling the JS_EvaluateScript with a non-NULL filename argument.

However, the interfacing code of python-spidermonkey calls JS_EvaluateScript only inside the eval_script method, which as coded supplies source only as a string.

You should address your issue to the python-spidermonkey developer, or —better, if possible!— provide a patch for a, say, eval_file_script method :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top