简体   繁体   English

使用Python从文件中读取JavaScript变量

[英]Read JavaScript variables from a file with Python

I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database. 我在服务器端使用一些Python脚本将JavaScript文件编译为一个文件,并将有关这些文件的信息添加到数据库中。 For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this: 为了添加有关脚本的信息,我现在每个js文件都有yaml文件,里面有一些信息,如下所示:

title: Script title
alias: script_alias

I would like to throw away yaml that looks redundant here to me if I can read these variables directly from JavaScript that I could place in the very beginning of the file like this: 如果我可以直接从JavaScript中读取这些变量,我想把这些看起来多余的yaml扔给我,我可以放在文件的最开头,如下所示:

var title = "Script title";
var alias = "script_alias";

Is it possible to read these variables with Python easily? 是否可以轻松地使用Python读取这些变量?

Assuming you only want the two lines, and they are at the top of the file... 假设你只想要两条线,它们位于文件的顶部......

import re

js = open("yourfile.js", "r").readlines()[:2]

matcher_rex = re.compile(r'^var\s+(?P<varname>\w+)\s+=\s+"(?P<varvalue>[\w\s]+)";?$')
for line in js:
    matches = matcher_rex.match(line)
    if matches:
        name, value = matches.groups()
        print name, value

Have you tried storing the variables in a JSON format? 您是否尝试以JSON格式存储变量? Then, both javascript and python can easily parse the data and get the variables. 然后,javascript和python都可以轻松解析数据并获取变量。

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

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