Skip to content

Decorator to run a function in a different process

I use this technique when I need to run multiple functions inside different processes.

The decorator is used like this:

@run_in_sub_process
def example(foo="bar"):
    print(foo)

And the implementation looks like this:

import functools
import multiprocessing


def run_in_sub_process(func):
    @functools.wraps(func)
    def inner(*args, **kwargs):
        process = multiprocessing.Process(target=func, args=args, kwargs=kwargs)
        process.start()
        process.join()
    return inner