简体   繁体   English

如何使用PyV8从python中读取javascript值

[英]How to read javascript values from python with PyV8

I've implemented PyV8 into Python. 我已经将PyV8实现为Python。 I have an example javascript file that looks like this: 我有一个示例javascript文件,如下所示:

main-js.js: 主js.js:

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

How do I read each variable into Python with PyV8? 如何使用PyV8将每个变量读入Python? So far I've opened and read the file with this: ctxt.eval(open("main-js.js").read()). 到目前为止,我已经打开并读取了这个文件: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 由于缺乏pyv8的文档,很难找到

The JSContext object has a locals attribute which is a dictionary of the context's local variables. JSContext对象有一个locals属性,它是上下文的局部变量的字典。 So, you want ctxt.locals["numOne"] and so on. 所以,你想要ctxt.locals["numOne"]等等。

Another way to do it: eval() has a return value, which is the value of the last statement evaluated. 另一种方法: eval()有一个返回值,它是最后一个语句的值。 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. 所以你也可以执行一个JavaScript语句来评估你感兴趣的变量。在这种情况下你可以创建一个JavaScript数组,然后你可以将它们解压缩到你想要的Python变量中。 You could do this by appending the statement to the code you read from the file, or just execute a separate eval() for it: 您可以通过将语句附加到从文件中读取的代码来执行此操作,或者只为它执行单独的eval()

with PyV8.JSContext() as ctxt:
    with open("main-js.js") as jsfile:
        ctxt.eval(jsfile.read())
    numOne, numTwo, numThree = ctxt.eval("[numOne, numTwo, numThree]")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM