Skip to content

Instantly share code, notes, and snippets.

@flbraun
Forked from schlamar/processify.py
Last active September 30, 2021 12:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flbraun/8199fc1a41c2107982053aba809838c6 to your computer and use it in GitHub Desktop.
Save flbraun/8199fc1a41c2107982053aba809838c6 to your computer and use it in GitHub Desktop.
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
Copy link

M0dM commented Jul 8, 2021

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

@flbraun
Copy link
Author

flbraun commented Jul 8, 2021

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

Not at all, here you go.

@M0dM
Copy link

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