用于缩小 CSS 的 Python 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/222581/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:40:42  来源:igfitidea点击:

Python script for minifying CSS?

pythoncsscompressionminify

提问by Will Moffat

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 Utilsare overkill for this project).

我正在寻找一个简单的 Python 脚本,它可以在网站部署过程中缩小 CSS。(Python 是服务器上唯一支持的脚本语言,像CSS Utils这样成熟的解析器对于这个项目来说是多余的)。

Basically I'd like jsmin.pyfor CSS. A single script with no dependencies.

基本上我想要jsmin.py用于 CSS。没有依赖项的单个脚本。

Any ideas?

有任何想法吗?

回答by Borgar

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:

这对我来说似乎是一个很好的任务,因为它已经被搁置了一段时间。我在此展示我的第一个 python 脚本:

import sys, re

with 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\((["\'])([^)]*)\)', r'url()', 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])([0-9a-f])([0-9a-f])(\s|;)', r'#', css )

# fragment values can loose zeros
css = re.sub( r':\s*0(\.\d+([cm]m|e[mx]|in|p[ctx]))\s*;', r':;', css )

for rule in re.findall( r'([^{]+){([^}]*)}', css ):

    # we don't need spaces around operators
    selectors = [re.sub( r'(?<=[\[\(>+=])\s+|\s+(?=[=~^$*|>+\]\)])', r'', selector.strip() ) for selector in rule[0].split( ',' )]

    # order is important, but we still want to discard repetitions
    properties = {}
    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 declarations
    if 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).

我相信这是可行的,并且在最近的 Safari、Opera 和 Firefox 上输出它测试良好。它会破坏除下划线和 /**/ hacks 之外的 CSS hacks!如果您正在进行大量黑客攻击(或将它们放在单独的文件中),请不要使用压缩器。

Any tips on my python appreciated. Please be gentle though, it's my first time. :-)

对我的 python 的任何提示表示赞赏。请温柔点,这是我第一次。:-)

回答by Gregor Müllegger

There is a port of YUI's CSS compressor available for python.

有一个可用于 Python 的 YUI 的 CSS 压缩器端口。

Here is its project page on PyPi: http://pypi.python.org/pypi/cssmin/0.1.1

这是它在 PyPi 上的项目页面:http://pypi.python.org/pypi/cssmin/0.1.1

回答by Wtower

In case someone landed on this question and is using Django, there is a commonly used package for this matter called Django Compressor:

如果有人遇到这个问题并且正在使用 Django,有一个常用的包称为Django Compressor

Compresses linked and inline JavaScript or CSS into a single cached file.

  • JS/CSS belong in the templates

  • Flexibility

  • It doesn't get in the way

  • Full test suite

将链接和内联 JavaScript 或 CSS 压缩到单个缓存文件中。

  • JS/CSS 属于模板

  • 灵活性

  • 它不会妨碍

  • 完整的测试套件

回答by alexandrul

In the webassetsdocs you can find links to multiple compressors and compilers. From that list I have chosen pyScss, which also minifies the resulting CSS.

webassets文档中,您可以找到指向多个压缩器和编译器的链接。我从该列表中选择了pyScss,这也缩小了生成的 CSS。

If you need just a CSS compressor you can try csscompressor:

如果你只需要一个 CSS 压缩器,你可以试试csscompressor

Almost exact port of YUI CSS Compressor. Passes all original unittests.

YUI CSS Compressor 的几乎完全相同的端口。通过所有原始单元测试。

A more generic tool is css-html-prettify:

一个更通用的工具是css-html-prettify

StandAlone Async single-file cross-platform Unicode-ready Python3 Prettifier Beautifier for the Web.

用于 Web 的独立异步单文件跨平台 Unicode 就绪 Python3 Prettifier Beautifier。

回答by Yahya Yahyaoui

There is a nice online tool cssminifierwhich has also an API which is pretty simple and easy to use. I made a small python script that posts the CSS file content to that tool's API, returns the minifed CSS and saves it into a file "style.min.css". I like it because it is a small code that may be nicely integrated in an automated deployment script:

有一个不错的在线工具cssminifier,它还有一个非常简单易用的 API。我制作了一个小的 python 脚本,将 CSS 文件内容发布到该工具的 API,返回缩小的 CSS 并将其保存到文件“style.min.css”中。我喜欢它,因为它是一小段代码,可以很好地集成到自动部署脚本中:

import requests
f = open("style.css", "r")
css_text = f.read()
f.close()
r = requests.post("http://cssminifier.com/raw", data={"input":css_text})
css_minified = r.text
f2 = open("style.min.css", "w")
f2.write(css_minified)
f2.close()

回答by Jeffrey Martinez

I don't know of any ready made python css minifiers, but like you said css utils has the option. After checking and verifying that the license allows for it, you could go through the source code and snip out the portions that do the minifying yourself. Then stick this in a single script and voila! There you go.

我不知道有任何现成的 python css minifiers,但就像你说的 css utils 有这个选项。在检查并验证许可证允许之后,您可以浏览源代码并剪掉自己进行缩小的部分。然后将其粘贴在单个脚本中,瞧!你去吧。

As a head start, the csscombine function in .../trunk/src/cssutils/script.py seems to do the work of minifying somewhere around line 361 (I checked out revision 1499). Note the boolean function argument called "minify".

作为开端,.../trunk/src/cssutils/script.py 中的 csscombine 函数似乎在第 361 行(我检查了修订版 1499)附近的某处进行了缩小工作。请注意名为“minify”的布尔函数参数。