python replace print with function

python

Solution

Using editor

I don't know which editor you're using, but if it supports RegEx search and replace, you can try something like this:

Replace: print "(.*?)"
With: scribble( "\1" )

I tested this in Notepad++.

Using Python

Alternatively, you can do it with Python itself:

import re

f = open( "code.py", "r" )
newsrc = re.sub( "print \"(.*?)\"", "scribble( \"\\1\" )", f.read() )
f.close()

f = open( "newcode.py", "w" )
f.write( newsrc )
f.close()

Problem

I'm using python 2.6 and have a bunch of print statments in my long program. How can I replace them all with my custom print function, lets call it scribble(). Because if I just search and replace print with scribble( there is no closing parentesis. I think regular expressions is how, but I have experimented with them for a day or so and I can't seem to get it to work.

Original source