console.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. """
  2. Internal module for console introspection
  3. """
  4. from __future__ import annotations
  5. from shutil import get_terminal_size
  6. def get_console_size() -> tuple[int | None, int | None]:
  7. """
  8. Return console size as tuple = (width, height).
  9. Returns (None,None) in non-interactive session.
  10. """
  11. from pandas import get_option
  12. display_width = get_option("display.width")
  13. display_height = get_option("display.max_rows")
  14. # Consider
  15. # interactive shell terminal, can detect term size
  16. # interactive non-shell terminal (ipnb/ipqtconsole), cannot detect term
  17. # size non-interactive script, should disregard term size
  18. # in addition
  19. # width,height have default values, but setting to 'None' signals
  20. # should use Auto-Detection, But only in interactive shell-terminal.
  21. # Simple. yeah.
  22. if in_interactive_session():
  23. if in_ipython_frontend():
  24. # sane defaults for interactive non-shell terminal
  25. # match default for width,height in config_init
  26. from pandas._config.config import get_default_val
  27. terminal_width = get_default_val("display.width")
  28. terminal_height = get_default_val("display.max_rows")
  29. else:
  30. # pure terminal
  31. terminal_width, terminal_height = get_terminal_size()
  32. else:
  33. terminal_width, terminal_height = None, None
  34. # Note if the User sets width/Height to None (auto-detection)
  35. # and we're in a script (non-inter), this will return (None,None)
  36. # caller needs to deal.
  37. return display_width or terminal_width, display_height or terminal_height
  38. # ----------------------------------------------------------------------
  39. # Detect our environment
  40. def in_interactive_session() -> bool:
  41. """
  42. Check if we're running in an interactive shell.
  43. Returns
  44. -------
  45. bool
  46. True if running under python/ipython interactive shell.
  47. """
  48. from pandas import get_option
  49. def check_main():
  50. try:
  51. import __main__ as main
  52. except ModuleNotFoundError:
  53. return get_option("mode.sim_interactive")
  54. return not hasattr(main, "__file__") or get_option("mode.sim_interactive")
  55. try:
  56. # error: Name '__IPYTHON__' is not defined
  57. return __IPYTHON__ or check_main() # type: ignore[name-defined]
  58. except NameError:
  59. return check_main()
  60. def in_ipython_frontend() -> bool:
  61. """
  62. Check if we're inside an IPython zmq frontend.
  63. Returns
  64. -------
  65. bool
  66. """
  67. try:
  68. # error: Name 'get_ipython' is not defined
  69. ip = get_ipython() # type: ignore[name-defined]
  70. return "zmq" in str(type(ip)).lower()
  71. except NameError:
  72. pass
  73. return False