Skip to content

Instantly share code, notes, and snippets.

@Chiron1991
Forked from schlamar/processify.py
Last active Jul 27, 2021
Embed
What would you like to do?
processify for Python 3
MIT License
Copyright (c) [year] [fullname]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
https://gist.github.com/schlamar/2311116
with Python 3 adaptations and some code formatting.
"""
import os
import sys
import traceback
from functools import wraps
from multiprocessing import Process, Queue
def processify(func):
"""
Decorator to run a function as a process.
Be sure that every argument and the return value
is *pickable*.
The created process is joined, so the code does not
run in parallel.
"""
def process_func(q, *args, **kwargs):
try:
ret = func(*args, **kwargs)
except Exception:
ex_type, ex_value, tb = sys.exc_info()
error = ex_type, ex_value, ''.join(traceback.format_tb(tb))
ret = None
else:
error = None
q.put((ret, error))
# register original function with different name
# in sys.modules so it is pickable
process_func.__name__ = func.__name__ + 'processify_func'
setattr(sys.modules[__name__], process_func.__name__, process_func)
@wraps(func)
def wrapper(*args, **kwargs):
q = Queue()
p = Process(target=process_func, args=(q,) + args, kwargs=kwargs)
p.start()
ret, error = q.get()
p.join()
if error:
ex_type, ex_value, tb_str = error
message = '%s (in subprocess)\n%s' % (str(ex_value), tb_str)
raise ex_type(message)
return ret
return wrapper
@processify
def test_function():
return os.getpid()
@processify
def test_deadlock():
return range(30000)
@processify
def test_exception():
raise RuntimeError('xyz')
def test():
print(os.getpid())
print(test_function())
print(len(test_deadlock()))
test_exception()
if __name__ == '__main__':
test()
@M0dM

This comment has been minimized.

Copy link

@M0dM M0dM commented Jul 8, 2021

Hi @Chiron1991 would you mind to add a MIT license to this snippet ?

@Chiron1991

This comment has been minimized.

Copy link
Owner Author

@Chiron1991 Chiron1991 commented Jul 8, 2021

Hi @Chiron1991 would you mind to add a MIT license to this snippet ?

Not at all, here you go.

@M0dM

This comment has been minimized.

Copy link

@M0dM M0dM commented Jul 15, 2021

Thank you 🎆

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment