3

I use some Python scripts on server-side to compile JavaScript files to one file and also add information about these files into database. For adding the information about the scripts I now have yaml file for each js file with some info inside it looking like this:

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:

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

Is it possible to read these variables with Python easily?

2 Answers 2

4

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

1 Comment

Is there a reason that you're using [a-zA-Z0-9_] instead of \w?
2

Have you tried storing the variables in a JSON format? Then, both javascript and python can easily parse the data and get the variables.

Comments

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.