Skip to content

Instantly share code, notes, and snippets.

@vxgmichel
Created September 29, 2017 16:30
Show Gist options
  • Save vxgmichel/dd039b950f5f84926aead8c1403d93c2 to your computer and use it in GitHub Desktop.
Save vxgmichel/dd039b950f5f84926aead8c1403d93c2 to your computer and use it in GitHub Desktop.
Protecting against SIGINT using ThreadPoolExecutor
# Common imports
from time import sleep
# Synchronous imports
from concurrent.futures import ThreadPoolExecutor
# Asynchronous imports
# from gevent.threadpool import ThreadPoolExecutor
def protect(fn, *args, **kwargs):
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(fn, *args, **kwargs)
return future.result()
def ask(arg):
for i in range(5):
print('<debug>', i)
sleep(1)
return arg
def main():
while 'n' not in input('Run ([y]/n)? ').lower():
try:
print(protect(ask, 'hello'))
except KeyboardInterrupt:
print('Interrupted')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment