Python Callbacks Example


Python
For more information on Python, visit python.org


Description


The purpose of this python snippit is to show how to do a callback in python.


Required Modules:


Python Native multiprocessing


Code:


"""Test Callback Function"""
import multiprocessing as mp

def count(countvar):
    """This function will just count to 100"""
    print('Incoming Variable is equal to ' + str(countvar))
    countvar = 0
    while countvar < 1000000:
        countvar = countvar + 1

    response = "Count is set to " + str(countvar)
    return response

def callback(result):
    """This will print the result calleded via the callback."""

    if result is not None:
        print(str(result[0]) + ' Callback Succeeded')
    else:
        print("Callback Failure")

#
# Create pool
#
PROCESSES = 4
print('Creating pool with %d processes\n' % PROCESSES)
POOL = mp.Pool(PROCESSES)
print('POOL = %s' % POOL)
print()

TEST = None

MP_CALLBACK = None
RESULT = None
# RESULT = POOL.apply_async(count, (TEST, ), callback=MP_CALLBACK)
RESULT = POOL.map_async(count, (TEST, ), callback=callback)
POOL.close()
POOL.join()