Queer European MD passionate about IT
浏览代码

Implemented non-unix timed_input function

Davte 5 年之前
父节点
当前提交
57d3efc3b5
共有 2 个文件被更改,包括 36 次插入3 次删除
  1. 1 1
      filebridging/__init__.py
  2. 35 2
      filebridging/utilities.py

+ 1 - 1
filebridging/__init__.py

@@ -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"

+ 35 - 2
filebridging/utilities.py

@@ -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)