Advertisement
Guest User

Untitled

a guest
Jun 23rd, 2021
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. import threading
  2. import queue
  3. def call_threadily(func, *args, **kwargs):
  4. result = queue.Queue(1)
  5. def f():
  6. try:
  7. result.put(("success", func(*args, **kwargs)))
  8. except Exception as e:
  9. result.put(("failure", e))
  10.  
  11. t = threading.Thread(target=f)
  12. t.start()
  13. t.join()
  14. assert result.full()
  15. state, value = result.get()
  16. if state == "success":
  17. return value
  18. else:
  19. raise Exception("Thread raised an exception!") from value
  20.  
  21. def oops():
  22. return 1/0
  23.  
  24. print(call_threadily(oops))
  25.  
  26. """
  27. result:
  28.  
  29. Traceback (most recent call last):
  30. File "C:\Users\Kevin\Desktop\test.py", line 7, in f
  31. result.put(("success", func(*args, **kwargs)))
  32. File "C:\Users\Kevin\Desktop\test.py", line 22, in oops
  33. return 1/0
  34. ZeroDivisionError: division by zero
  35.  
  36. The above exception was the direct cause of the following exception:
  37.  
  38. Traceback (most recent call last):
  39. File "C:\Users\Kevin\Desktop\test.py", line 24, in <module>
  40. print(call_threadily(oops))
  41. File "C:\Users\Kevin\Desktop\test.py", line 19, in call_threadily
  42. raise Exception("Thread raised an exception!") from value
  43. Exception: Thread raised an exception!
  44. """
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement