I'm using PyV8 to execute Javascript programs from Python. I had a problem executing "document.write", but found the solution here (using Mock Document): Executing Javascript from Python
Now,I'm facing an other problem. I want to execute a prompt command javascript from python. The effect of the result should be like a simple python raw_input. I give an example:
var a, b, c, d;
prompt(a);
c = a
prompt(b);
c = c + b
d = a * b
document.write(c)
document.write(d)
using PyV8, the evaluation of this script should evaluate the first line, stop at prompt(a) asking me to introduce the value of a (DOS line command), then resume the evaluation till next prompt, and so on. Thks in advance.
2 Answers 2
Injecting a Python function into JavaScript context is actually very simple - you assign that function to a local variable via JSContext.locals object:
ctx = PyV8.JSContext()
ctx.enter()
ctx.locals.prompt = raw_input
ctx.eval('var a = prompt("js> ");')
And all the sudden you can use that Python function from JavaScript exactly like you would do it in Python.
I would normally link to the documentation but PyV8 documentation doesn't appear to be available anywhere with the proper MIME type.
Comments
if there is no prompt() function in PyV8 then you could add it the same way as document object is added in the example you cited.
for js in iter(raw_input("js> "), ""): print(ctx.eval(js))iter(lambda: raw_...instead ofiter(raw_.... The intent is to provide the simplest interactive javascript console.prompt()in it or you'd like to reproduce its behavior (show dialog box, return input) in Python e.g., using tkinter, wxpython?