1

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

1 Answer 1

3

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]")
Sign up to request clarification or add additional context in comments.

2 Comments

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
NEVERMIND. I figured it out :) Thanks a bunch

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.