Varsub.py
Varsub.py is a python script to define and use variables in arbitrary files, also known as string interpolation with evaluation of embedded expressions (for a different approach see see this recipe) . It evolved from the wish to use easy recognizable names for colours in CSS stylesheets so its use is probably best illustrated with a CSS example.
Given a file like this:
/* meaningfull names for often used colors
$(themebackground)=#eeeeee
$(thememain)=#dd9999
*/
h2 { background-color:$theme-background;
color:$theme-main}
Varsub.py will produce this:
/* meaningfull names for often used colors
$(themebackground)='#eeeeee'
$(thememain)='#dd9999'
*/
h2 { background-color:#eeeeee;
color:#dd9999}
This way it it is quite easy to refer
to colors or other entities by meaningfull
names and changing a value is simpler and
less error prone as well: changing the
definition of a variable in a single place
is all there is to it.
Expressions
Varsub.py is capable of far more than illustrated in the previous example: the value that is assigned to a variable in its definition is actually evaluated as a python expression. So almost anything is possible even refering to previously defined variables:
$a=40+2 $b=2 $c="a + b" $(d)=1*1*1=1 $a times $b equals $c .... $dwill produce
$a=40+2 $b=2 $c="a + b" $(d)=1*1*1=1 42 times 2 equals 44 .... 1*1*1=1Note the use of quotes when the expression consists of words seperated by whitespace. The use of parentheses in the definition of $d prevents the right hand side portion from being evaluated.
Usage
Varsub.py is a python module and its primary use is as a reusable component in other programs, but a simple interface for commandline use is provided as well.
Usage: Varsub.py [options] [[-]file1 [[-]file2 ...]]
Filenames starting with a minussign are read but
produce no output. If such filenames are used,
preceed the list of filenames with '--' to
signal the end-of-options.
Example: Varsub.py -- -constants.def style.def > style.css
Options:
-h, --help show this help message and exit
-o FILE, --outfile=FILE
print to FILE instead to stdout
-t, --test run testsuite and then abort
Installation
Installation is quite simple:
- download Varsub.py
- install it in your
site-packages
You now should be able to test it with:
python -m Varsub -t
Installation is so simple that I didn't bother to write a setup script. It is tested on python 2.6.2. and 3.0 and released as free software under GPL.