cursor.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # Copyright 2022 The HuggingFace Team and Brian Chao. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """
  15. A utility for showing and hiding the terminal cursor on Windows and Linux, based on https://github.com/bchao1/bullet
  16. """
  17. import os
  18. import sys
  19. from contextlib import contextmanager
  20. # Windows only
  21. if os.name == "nt":
  22. import ctypes
  23. import msvcrt # noqa
  24. class CursorInfo(ctypes.Structure):
  25. # _fields is a specific attr expected by ctypes
  26. _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)]
  27. def hide_cursor():
  28. if os.name == "nt":
  29. ci = CursorInfo()
  30. handle = ctypes.windll.kernel32.GetStdHandle(-11)
  31. ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
  32. ci.visible = False
  33. ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
  34. elif os.name == "posix":
  35. sys.stdout.write("\033[?25l")
  36. sys.stdout.flush()
  37. def show_cursor():
  38. if os.name == "nt":
  39. ci = CursorInfo()
  40. handle = ctypes.windll.kernel32.GetStdHandle(-11)
  41. ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci))
  42. ci.visible = True
  43. ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci))
  44. elif os.name == "posix":
  45. sys.stdout.write("\033[?25h")
  46. sys.stdout.flush()
  47. @contextmanager
  48. def hide():
  49. "Context manager to hide the terminal cursor"
  50. try:
  51. hide_cursor()
  52. yield
  53. finally:
  54. show_cursor()