Implemented non-unix timed_input function
This commit is contained in:
parent
942536d66a
commit
57d3efc3b5
@ -13,6 +13,6 @@ __author__ = "Davide Testa"
|
||||
__email__ = "davide@davte.it"
|
||||
__credits__ = []
|
||||
__license__ = "GNU General Public License v3.0"
|
||||
__version__ = "0.0.2"
|
||||
__version__ = "0.0.3"
|
||||
__maintainer__ = "Davide Testa"
|
||||
__contact__ = "t.me/davte"
|
||||
|
@ -4,6 +4,8 @@ import logging
|
||||
import shutil
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
|
||||
from typing import Union
|
||||
|
||||
units_of_measurements = {
|
||||
@ -86,11 +88,17 @@ def timed_action(interval: Union[int, float, datetime.timedelta] = None):
|
||||
return timer
|
||||
|
||||
|
||||
def timed_input(message: str = None,
|
||||
timeout: int = 5):
|
||||
def unix_timed_input(message: str = None,
|
||||
timeout: int = 5):
|
||||
"""Print `message` and return input within `timeout` seconds.
|
||||
|
||||
If nothing was entered in time, return None.
|
||||
This works only on unix systems, since `signal.alarm` is needed.
|
||||
"""
|
||||
class TimeoutExpired(Exception):
|
||||
pass
|
||||
|
||||
# noinspection PyUnusedLocal
|
||||
def interrupted(signal_number, stack_frame):
|
||||
"""Called when read times out."""
|
||||
raise TimeoutExpired
|
||||
@ -108,3 +116,28 @@ def timed_input(message: str = None,
|
||||
logging.info("Timeout!")
|
||||
signal.alarm(0)
|
||||
return given_input
|
||||
|
||||
|
||||
def non_unix_timed_input(message: str = None,
|
||||
timeout: int = 5):
|
||||
"""Print message and wait `timeout` seconds before reading standard input.
|
||||
|
||||
This works on all systems, but cannot last less then `timeout` even if
|
||||
user presses enter.
|
||||
"""
|
||||
print(message, end='')
|
||||
time.sleep(timeout)
|
||||
input_ = sys.stdin.readline()
|
||||
if not input_.endswith("\n"):
|
||||
print() # Print end of line
|
||||
if input_:
|
||||
return input_
|
||||
return
|
||||
|
||||
|
||||
def timed_input(message: str = None,
|
||||
timeout: int = 5):
|
||||
"""Print `message` and return input within `timeout` seconds."""
|
||||
if sys.platform.startswith('linux'):
|
||||
return unix_timed_input(message=message, timeout=timeout)
|
||||
return non_unix_timed_input(message=message, timeout=timeout)
|
||||
|
Loading…
x
Reference in New Issue
Block a user