2

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.

Community
  • 1
  • 1
Academia
  • 3,984
  • 6
  • 32
  • 49
  • `for js in iter(raw_input("js> "), ""): print(ctx.eval(js))` – jfs Jun 03 '12 at 12:22
  • J.F.Sebastian: Thks any way, but that's not what I'm asking for!!! I think the question is clear. If not tell me so I can made it clear for every one. – Academia Jun 03 '12 at 13:53
  • there should be `iter(lambda: raw_...` instead of `iter(raw_...`. The intent is to provide the simplest interactive javascript console. – jfs Jun 03 '12 at 14:02
  • J.F.Sebastian: That's not what I want, but thks any way for responding and giving time. I wnat to execute Javascript programs from Python programs. Prompt is a Javascript function that reads a value from keyboard. – Academia Jun 03 '12 at 14:44
  • Do you want to execute a javascript code that calls `prompt()` in it or you'd like to reproduce its behavior (show dialog box, return input) in Python e.g., using tkinter, wxpython? – jfs Jun 03 '12 at 15:36
  • Yeah, "I want to execute a prompt command javascript from python" is not exactly clear. I know those words, but don't understand them in that order... – kindall Jun 04 '12 at 03:52
  • I'm really sorry for the late response. I just added a simple example to show u what I'm looking for. – Academia Jun 04 '12 at 10:12

2 Answers2

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.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
1

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.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • 1
    @user1038382: "no success" is not very specific. Create a minimal complete example that tries to execute 'prompt("foo", "bar")' and post the code and all errors it produces. – jfs Jun 06 '12 at 12:59