FocusedWolf

Python: MonitorOff

May 13th, 2024 (edited)
1,166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.93 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # Version 5
  4.  
  5. # NOTE: Windows users need to install pypiwin32 for this script to work:
  6. #       Run CMD as administrator > pip install pywin32
  7.  
  8. import platform
  9. def screenOff():
  10.     system = platform.system()
  11.     if system == 'Linux':
  12.         import os
  13.         import subprocess
  14.  
  15.         session = os.environ.get('XDG_SESSION_TYPE')
  16.  
  17.         if session == 'x11':
  18.             # NOTE: To prevent passworded lockscreen from appearing for XFCE:
  19.             #       Start > Power Manager > Security:
  20.             #           Automatically lock the session: Never
  21.             #           [ ] Lock screen when system is going to sleep
  22.  
  23.             # SOURCE: https://stackoverflow.com/questions/60851689/turn-screen-off-in-linux-via-python3
  24.             # SOURCE: https://askubuntu.com/questions/38776/trigger-screensaver-off-monitor
  25.             # SOURCE: https://ubuntuforums.org/showthread.php?t=1607724
  26.             # SOURCE: https://wiki.archlinux.org/title/Display_Power_Management_Signaling
  27.             subprocess.run(['xset', 'dpms', 'force', 'suspend'])
  28.         elif session == 'wayland':
  29.             # NOTE: To prevent passworded lockscreen from appearing for KDE:
  30.             #       Start > Screen Locking:
  31.             #           Lock screen automatically: [ ] After [5 minutes]
  32.             #                                      [ ] After waking from sleep
  33.  
  34.             # SOURCE: https://askubuntu.com/questions/1316097/how-to-turn-off-the-monitor-via-command-on-wayland-kde-plasma
  35.             subprocess.run(['kscreen-doctor', '--dpms', 'off'])
  36.         else:
  37.             print('Could not determine the display server.')
  38.     elif system == 'Windows':
  39.         # pip install pywin32
  40.         import win32con
  41.         import win32gui
  42.         # SOURCE: https://stackoverflow.com/questions/70965202/python-turn-screen-on-and-off-on-windows
  43.         win32gui.PostMessage(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, win32con.SC_MONITORPOWER, 2)
  44.     else:
  45.         print('Unknown OS detected:', system)
  46.  
  47. # ----
  48.  
  49. import threading
  50. cancelled = threading.Event()
  51.  
  52. import time
  53. def watch_escape():
  54.     system = platform.system()
  55.     if system == 'Windows':
  56.         import msvcrt
  57.         while not cancelled.is_set():
  58.             if msvcrt.kbhit():
  59.                 key = msvcrt.getch()
  60.                 if key == b'\x1b': # Esc
  61.                     cancelled.set()
  62.                     return
  63.             time.sleep(0.01)
  64.     else:
  65.         import select
  66.         import sys
  67.         import termios
  68.         import tty
  69.         fd = sys.stdin.fileno()
  70.         old = termios.tcgetattr(fd)
  71.         try:
  72.             tty.setcbreak(fd)
  73.             while not cancelled.is_set():
  74.                 ready, _, _ = select.select([sys.stdin], [], [], 0.1)
  75.                 if ready:
  76.                     if sys.stdin.read(1) == '\x1b':
  77.                         cancelled.set()
  78.                         return
  79.         finally:
  80.             termios.tcsetattr(fd, termios.TCSADRAIN, old)
  81.  
  82. def countdown(message, seconds):
  83.     while seconds > 0:
  84.         if cancelled.is_set():
  85.             return False
  86.         print(f'\r{message.format(seconds)} Quit → Esc', end='', flush=True)
  87.         for _ in range(10):
  88.             if cancelled.is_set():
  89.                 return False
  90.             time.sleep(0.1)
  91.         seconds -= 1
  92.     return True
  93.  
  94. # ----
  95.  
  96. def main():
  97.     t = threading.Thread(target=watch_escape)
  98.     t.start()
  99.  
  100.     # This delay is to give the mouse a chance to stop moving.
  101.     # Mouse-wire tension + slippery feet can cause unintended mouse movement which will wake up the monitor prematurely.
  102.     if not countdown('Turning off monitor in {} seconds . . .', 5):
  103.         cancelled.set()
  104.         t.join() # Wait for thread so terminal restores.
  105.  
  106.         print()
  107.         return
  108.  
  109.     cancelled.set()
  110.     t.join() # Wait for thread so terminal restores.
  111.  
  112.     screenOff()
  113.     print()
  114.  
  115. if __name__ == '__main__':
  116.     main()
Advertisement
Add Comment
Please, Sign In to add comment