Skip to content

Instantly share code, notes, and snippets.

@arount
Created January 19, 2018 09:14
Show Gist options
  • Save arount/f9169c8f5d3bc2298aba807d67b87f11 to your computer and use it in GitHub Desktop.
Save arount/f9169c8f5d3bc2298aba807d67b87f11 to your computer and use it in GitHub Desktop.
Python (2/3) breakable-input
#!/usr/env/bin python
import sys
import os
import time
import fcntl
class BreakableInput(object):
'''
Breakable input() implementation.
'''
# To keep consistency BreakableInput must be a singleton
_instance = None
def __init__(self):
'''
Set stdin reading mode in char by char.
Lol, rtfm buddy.
'''
fl = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, fl | os.O_NONBLOCK)
@classmethod
def get_instance(cls):
'''
Singleton method
'''
if cls._instance is None:
cls._instance = cls()
return cls._instance
def input(self, timeout, tick=0.001):
'''
Make the "timeoutable" input().
'''
_start_time = time.time()
_passed_time = 0
_input = ''
while True:
try:
stdin = sys.stdin.read(1)
except IOError:
pass
else:
if stdin not in ['\n', '\r']:
_input += stdin
else:
return _input
# Compute timeout
_passed_time += time.time() - _start_time
_start_time = time.time()
if _passed_time >= timeout:
return
time.sleep(tick)
# Usage example
binput = BreakableInput.get_instance()
print(binput.input(10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment