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.

7
  • for js in iter(raw_input("js> "), ""): print(ctx.eval(js)) Commented Jun 3, 2012 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. Commented Jun 3, 2012 at 13:53
  • there should be iter(lambda: raw_... instead of iter(raw_.... The intent is to provide the simplest interactive javascript console. Commented Jun 3, 2012 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. Commented Jun 3, 2012 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? Commented Jun 3, 2012 at 15:36

2 Answers 2

2
+25

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.