I'm looking for a simple Python script that can minify CSS as part of a web-site deployment process. (Python is the only scripting language supported on the server and full-blown parsers like CSS Utils are overkill for this project).
Basically I'd like jsmin.py for CSS. A single script with no dependencies.
Any ideas?
Answer
This seemed like a good task for me to get into python, which has been pending for a while. I hereby present my first ever python script:
import sys, rewith open( sys.argv[1] , 'r' ) as f:css = f.read()# remove comments - this will break a lot of hacks :-P
css = re.sub( r'\s*/\*\s*\*/', "$$HACK1$$", css ) # preserve IE<6 comment hack
css = re.sub( r'/\*[\s\S]*?\*/', "", css )
css = css.replace( "$$HACK1$$", '/**/' ) # preserve IE<6 comment hack# url() doesn't need quotes
css = re.sub( r'url\((["\'])([^)]*)\1\)', r'url(\2)', css )# spaces may be safely collapsed as generated content will collapse them anyway
css = re.sub( r'\s+', ' ', css )# shorten collapsable colors: #aabbcc to #abc
css = re.sub( r'#([0-9a-f])\1([0-9a-f])\2([0-9a-f])\3(\s|;)', r'#\1\2\3\4', css )# fragment values can loose zeros
css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;', r':\1;', css )for rule in re.findall( r'([^{]+){([^}]*)}', css ):# we don't need spaces around operatorsselectors = [re.sub( r'(?<=[\[\(>+=])\s+|\s+(?=[=~^$*|>+\]\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )]# order is important, but we still want to discard repetitionsproperties = {}porder = []for prop in re.findall( '(.*?):(.*?)(;|$)', rule[1] ):key = prop[0].strip().lower()if key not in porder: porder.append( key )properties[ key ] = prop[1].strip()# output rule if it contains any declarationsif properties:print "%s{%s}" % ( ','.join( selectors ), ''.join(['%s:%s;' % (key, properties[key]) for key in porder])[:-1] )
I believe this to work, and output it tests fine on recent Safari, Opera, and Firefox. It will break CSS hacks other than the underscore & /**/ hacks! Do not use a minifier if you have a lot of hacks going on (or put them in a separate file).
Any tips on my python appreciated. Please be gentle though, it's my first time. :-)
I have an numpy array of forma = [1,2,3]which I want to save to a .txt file such that the file looks like:1 2 3If I use numpy.savetxt then I get a file like:1
2
3There should be a easy solution to this…
I dont think this is possible, but I want to handle exceptions from argparse myself.For example:import argparse
parser = argparse.ArgumentParser()
parser.add_argument(--foo, help=foo help, required=Tru…
The web server works (python flask) but when I go to the website, where the value of animal should be (dog) it shows the variable name animal. (There is more to the code but this is the most simplistic…
When I load a number with e form a JSON dump with YAML, the number is loaded as a string and not a float.I think this simple example can explain my problem.import json
import yamlIn [1]: import jsonIn …
Im plotting two data series with Pandas with seaborn imported. Ideally I would like the horizontal grid lines shared between both the left and the right y-axis, but Im under the impression that this is…
How can the line width of the error bar caps in Matplotlib be changed?I tried the following code:(_, caplines, _) = matplotlib.pyplot.errorbar(data[distance], data[energy], yerr=data[energy sigma],cap…
CPython has a strange behaviour where it sets modules to None during shutdown. This screws up error logging during shutdown of some multithreading code Ive written.I cant find any documentation of this…
Answered I ended up going with pickle at the end anywayOk so with some advice on another question I asked I was told to use pickle to save a dictionary to a file. The dictionary that I was trying to sa…
I want to create a class that behaves like collections.defaultdict, without having the usage code specify the factory. EG:
instead of class Config(collections.defaultdict):passthis:Config = functools.p…