Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I've implemented PyV8 into Python. I have an example javascript file that looks like this:

main-js.js:

var numOne = 1+2;
var numTwo = 3+1;
var numThree = 5;

How do I read each variable into Python with PyV8? So far I've opened and read the file with this: ctxt.eval(open("main-js.js").read()). But i don't know how to grab each variable from the file. This is hard to find due to the lack of documentation with pyv8

share|improve this question

1 Answer 1

The JSContext object has a locals attribute which is a dictionary of the context's local variables. So, you want ctxt.locals["numOne"] and so on.

Another way to do it: eval() has a return value, which is the value of the last statement evaluated. So you could also execute a JavaScript statement that evaluates the variables you're interested in. In this case you could just create a JavaScript array of them, which you can then unpack into the Python variables you want. You could do this by appending the statement to the code you read from the file, or just execute a separate eval() for it:

with PyV8.JSContext() as ctxt:
    with open("main-js.js") as jsfile:
        ctxt.eval(jsfile.read())
    numOne, numTwo, numThree = ctxt.eval("[numOne, numTwo, numThree]")
share|improve this answer
    
thanks kindall! –  user1906825 May 16 '13 at 19:33
    
Very quick one more. What if I have a function in my javascript that returns a value. For instance: function getStr(){ return "hello" } How would I call the function and pull the return value with pyv8 –  user1906825 May 16 '13 at 19:38
    
NEVERMIND. I figured it out :) Thanks a bunch –  user1906825 May 16 '13 at 19:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.