Mainly Tech projects on Python and Electronic Design Automation.

Wednesday, June 06, 2007

My First Python one-liner

I created my first Python one-liner, to be used in anger today!
I was working on Unix, and because I know and use the normal command line utilities sed/grep/awk/perl etc, as well as Python, I tend to not use Python for one-liners (even very long one-liners), as Pythons syntax isn't up for it, and the other tools are in their element.
Today I was installing four simulation/verification packages from Cadence. We use the modules utility to allow us to easily access tools, but these new tools had what I was told was a complex setup script to be sourced that did a lot before setting environment variables to appropriate values.

I decided I needed to see what the changes to the environment were so needed to create a sorted list of environment variables before & after sourcing the setup, and then doing a gvimdiff. I could not use env|sort as our environment has a few variables with multi-line string values which are printed on separate lines and so mess with the sort.

I remembered that pprint sorts dictionaries and prints string values with escaped versions of newlines so came up with:
 python -c 'import os, pprint; pprint.pprint(dict(os.environ))' 

The dict() is needed as os.environ is not a true dictionary, it can interact with calls to putenv() and unsetenv.

Here is a sample session showing how it prints newlines in values:
bash$ export XX='Spam
bash$ python -c 'import os, pprint; pprint.pprint(dict(os.environ))'|fgrep XX
'XX': 'Spam\nHam',

- Paddy.


  1. This is quite nice. Thanks! I will use it.

  2. Oh no, A Python one-liner being RE-used!!

    Shock, horror :-)



Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

Blog Archive