기본 콘텐츠로 건너뛰기

[python] hooking in python

source: http://stackoverflow.com/questions/11635443/hooking-in-python

Hooking is a way to get your own code to execute when another system is running, whether that other system is an OS, a GUI, or whatever. A somewhat silly example in Python:
def Process(records, per_record_hook=None):
    "adds all records to XYZ system"
    for record in records:
        if per_record_hook:
            per_record_hook(record)
        XYZ.append(record)

def print_record(record):
    "print a '.' for each record (primitive counter)"
    print '.'
and then later:
Process(records_from_somewhere, per_record_hook=print_record)


<RESULT>

In [1]: records = [1,2,3]
In [2]: XYZ=[]
In [3]: %paste

def Process(records, per_record_hook=None):
    "adds all records to XYZ system"
    for record in records:
        if per_record_hook:
            per_record_hook(record)
        XYZ.append(record)

def print_record(record):
    "print a '.' for each record (primitive counter)"
    print '.'

## -- End pasted text --

In [4]: Process(records, per_record_hook=print_record)
.
.
.

In [5]: XYZ

Out[5]: [1, 2, 3]

댓글