| 1 |
# from https://gist.github.com/schlamar/2311116 |
| 2 |
import os |
| 3 |
import sys |
| 4 |
import traceback |
| 5 |
from functools import wraps |
| 6 |
from multiprocessing import Process, Queue |
| 7 |
|
| 8 |
|
| 9 |
def processify(func): |
| 10 |
'''Decorator to run a function as a process. |
| 11 |
Be sure that every argument and the return value |
| 12 |
is *pickable*. |
| 13 |
The created process is joined, so the code does not |
| 14 |
run in parallel. |
| 15 |
''' |
| 16 |
|
| 17 |
def process_func(q, *args, **kwargs): |
| 18 |
try: |
| 19 |
ret = func(*args, **kwargs) |
| 20 |
except Exception: |
| 21 |
ex_type, ex_value, tb = sys.exc_info() |
| 22 |
error = ex_type, ex_value, ''.join(traceback.format_tb(tb)) |
| 23 |
ret = None |
| 24 |
else: |
| 25 |
error = None |
| 26 |
|
| 27 |
q.put((ret, error)) |
| 28 |
|
| 29 |
# register original function with different name |
| 30 |
# in sys.modules so it is pickable |
| 31 |
process_func.__name__ = func.__name__ + 'processify_func' |
| 32 |
setattr(sys.modules[__name__], process_func.__name__, process_func) |
| 33 |
|
| 34 |
@wraps(func) |
| 35 |
def wrapper(*args, **kwargs): |
| 36 |
q = Queue() |
| 37 |
p = Process(target=process_func, args=[q] + list(args), kwargs=kwargs) |
| 38 |
p.start() |
| 39 |
p.join() |
| 40 |
ret, error = q.get() |
| 41 |
|
| 42 |
if error: |
| 43 |
ex_type, ex_value, tb_str = error |
| 44 |
message = '%s (in subprocess)\n%s' % (ex_value.message, tb_str) |
| 45 |
raise ex_type(message) |
| 46 |
|
| 47 |
return ret |
| 48 |
return wrapper |
| 49 |
|
| 50 |
|
| 51 |
@processify |
| 52 |
def test_function(): |
| 53 |
return os.getpid() |
| 54 |
|
| 55 |
|
| 56 |
@processify |
| 57 |
def test_exception(): |
| 58 |
raise RuntimeError('xyz') |
| 59 |
|
| 60 |
|
| 61 |
def test(): |
| 62 |
print(os.getpid()) |
| 63 |
print(test_function()) |
| 64 |
test_exception() |
| 65 |
|
| 66 |
if __name__ == '__main__': |
| 67 |
test() |