Created
September 29, 2017 16:30
-
-
Save vxgmichel/dd039b950f5f84926aead8c1403d93c2 to your computer and use it in GitHub Desktop.
Protecting against SIGINT using ThreadPoolExecutor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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