Skip to content

Instantly share code, notes, and snippets.

@pvsune
Created May 31, 2020 15:03
Show Gist options
  • Save pvsune/79a3125375e2f1ea4e68618f8f063b8c to your computer and use it in GitHub Desktop.
Save pvsune/79a3125375e2f1ea4e68618f8f063b8c to your computer and use it in GitHub Desktop.

Revisions

  1. pvsune created this gist May 31, 2020.
    24 changes: 24 additions & 0 deletions timeout.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    import logging
    from multiprocessing import Pool, TimeoutError


    logging.basicConfig(level=logging.INFO)


    def timeout(func, args=None, kwds=None, timeout=10):
    """Call function and wait until timeout.
    Cannot make into a decorator, fails in pickling function.
    """
    args = args or []
    kwds = kwds or {}
    with Pool(processes=1) as pool:
    res = pool.apply_async(func, args, kwds)
    try:
    return res.get(timeout)
    except TimeoutError:
    logging.exception(
    'Calling %s%s timed out after %ss',
    func.__name__, tuple(args), timeout
    )
    raise