em_er.py: change px sizes to em sizes in files

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
"""Change all sizes in px bigger than minsize to sizes in em.
Usage:
\t%prog [options] target_files"""
import re
import sys
from optparse import OptionParser
def px2em(s,div=16,mnm=7,mxm=1000):
tmp = int(s.replace('px',''))
if tmp >= mnm and tmp <= mxm:
return str(1./div * tmp)+'em'
else:
return s
def oParse(argv=sys.argv[1:]):
global prnt
parser = OptionParser(usage=__doc__)
parser.add_option('-s','--suffix',
action="store", dest='suffix', default='.new',
help='append suffix to modified filename, initial file\
is changed if none')
parser.add_option('-d','--divider',
action="store", dest='div', type='float', default='16',
help='alternate divider for changes')
parser.add_option('-v','--verbose',
action="store_true", dest='verb', default=False,
help='print changed files')
parser.add_option('-p','--pretend',
action="store_true", dest='sim', default=False,
help='don\'t write anything to files')
parser.add_option('--min',
action="store", dest='mnm', type='float', default=7,
help='minimum size to convert')
parser.add_option('--max',
action="store", dest='mxm', type='float', default=1000,
help='maximum size to convert')
(o,args) = parser.parse_args(argv)
prnt = o.verb or o.sim
return (o,args)
def main():
(o,args) = oParse()
if args == []:
raise ValueError("Arguments needed")
for arg in args:
if prnt:
print '\nFile:'+arg+o.suffix+'\n< BOF >'
f = open(arg)
lines = f.readlines()
for i in xrange(len(lines)):
pixies = re.finditer(r"(?iu)\b[\d]+ ?px\b",lines[i])
for token in pixies:
token = token.group(0)
lines[i] = lines[i].replace(token,px2em(token,o.div,o.mnm,o.mxm))
if prnt:
print '\t'+lines[i].replace('\n','')
f.close()
if not o.sim:
f = open(arg+o.suffix,'w')
f.writelines(lines)
if prnt:
print '< EOF >'
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception,err:
print err