Friday, October 19, 2012

Fun with IPython

Recently I had to git-rename (move) a few files according to a simple pattern (prepend "test_" to the name if it ends in ".py") and my shell fu had become rusty.  I wanted to do it in Python.

Enter IPython and its wonderful facility for mixing a little bit of shell goodness into your Python code.  Look what worked:

In [3]: fs = !ls

In [4]: fs
Out[4]: ['base.py', 'cache', '__init__.py', 'rss.py', 'util.py']

In [5]: for fn in fs:
   ...:     if fn.endswith('.py'):
   ...:         dest = 'test_' + fn
   ...:         !git mv $fn $dest
   ...:        

In [6]: !ls
cache  test_base.py  test___init__.py  test_rss.py  test_util.py
Neat, huh?