29
Jul

Installing cssutils for Python and Run an Example

The goal of this guide is to show you how to install and run the example Python script for cssutils from start to finsih. This was created while running Ubuntu, but can be applied and modified to any distribution. Open up a terminal and let’s get to it!

Step 1: Install easy_install For Python

The easy_install binary is a Python package manager that makes it easy to install cssutils. The following steps will get this installed:

sudo apt-get install curl
curl -O http://python-distribute.org/distribute_setup.py
sudo python distribute_setup.py

Step 2: Install cssutils Python Package

Now we’ll install the cssutils package for Python using easy_install.

sudo easy_install cssutils

Step 3: Prepare cssutils Example

Next, you can copy/paste the following example into your favorite text editor and save it (I saved it as cssutils_test.py).

import cssutils

css = u'''/* a comment with umlaut � */ 
     @namespace html "http://www.w3.org/1999/xhtml";
     @variables { BG: #fff }
     html|a { color:red; background: var(BG) }'''
sheet = cssutils.parseString(css)

for rule in sheet:
    if rule.type == rule.STYLE_RULE:
        # find property
        for property in rule.style:
            if property.name == 'color':
                property.value = 'green' 
                property.priority = 'IMPORTANT'
                break
        # or simply:
        rule.style['margin'] = '01.0eM' # or: ('1em', 'important')

sheet.encoding = 'ascii'
sheet.namespaces['xhtml'] = 'http://www.w3.org/1999/xhtml'
sheet.namespaces['atom'] = 'http://www.w3.org/2005/Atom'
sheet.add('atom|title {color: #000000 !important}')
sheet.add([email protected] "sheets/import.css";')

# cssutils.ser.prefs.resolveVariables == True since 0.9.7b2
print sheet.cssText

Step 4: Run cssutils Example

Finally, we can run the example.

python cssutils_test.py

Conclusions

I’m hoping this guide met the goal of teaching you how to install cssutils and run an example Python script to demonstrate some capabilities of cssutils. Feedback is welcomed and appreciated.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 0 Comment So Far

Share your thoughts, leave a comment!