views:

382

answers:

2

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)?

+2  A: 

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 :)

ΤΖΩΤΖΙΟΥ
Thanks, that's very helpful - I'll look into that!
AnC
+1  A: 

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);')
AnC