1729
1729

Reputation: 5051

How do I do monkeypatching in python?

I've had to do some introspection in python and it wasn't pretty:

name = sys._getframe(1).f_code
name = "%s:%d %s()" %(os.path.split(name.co_filename)[1],name.co_firstlineno,name.co_name)

To get something like

foo.py:22 bar() blah blah

In our debugging output.

I'd ideally like to prepend anything to stderr with this sort of information -- Is it possible to change the behaviour of print globally within python?

Upvotes: 9

Views: 604

Answers (2)

Pat Notz
Pat Notz

Reputation: 214346

The python inspect module makes this a lot easier and cleaner.

Upvotes: 1

Curt Hagenlocher
Curt Hagenlocher

Reputation: 20916

A print statement does its IO through "sys.stdout.write" so you can override sys.stdout if you want to manipulate the print stream.

Upvotes: 3

Related Questions