DeaD_EyE

xrandr restore old settings

Jun 26th, 2022 (edited)
150
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None
  1. #!/usr/bin/env python3
  2.  
  3. """
  4. https://askubuntu.com/questions/625761/how-to-change-displays-position-from-command-line
  5. """
  6.  
  7. import re
  8. import subprocess
  9. import json
  10. from pathlib import Path
  11.  
  12.  
  13. xrandr_reg = re.compile(r"^([\w-]+).+?(\d+x\d+)\+(\d+\+\d+)")
  14. config_file = Path.home().joinpath(".config/xrandr_config.json")
  15.  
  16.  
  17. def get_config():
  18.     proc = subprocess.run(["xrandr", "-q"], capture_output=True, encoding="utf8")
  19.     modes = []
  20.     for line in proc.stdout.splitlines():
  21.         if match := xrandr_reg.search(line):        
  22.             port, mode, pos = match.groups()
  23.             pos = pos.replace("+", "x")
  24.             modes.append((port, mode, pos))
  25.  
  26.     return modes
  27.  
  28.  
  29. def get_saved_config():
  30.     if config_file.exists():
  31.         with config_file.open() as fd:
  32.             return json.load(fd)
  33.     else:
  34.         with config_file.open("w") as fd:
  35.             config = get_config()
  36.             json.dump(config, fd)
  37.         return config
  38.  
  39.  
  40. def set_modes(config):
  41.     for port, mode, pos in config:
  42.         cmd = ["xrandr", "--output", port, "--mode", mode, "--pos", pos]
  43.         subprocess.run(cmd)
  44.  
  45.  
  46. if __name__ == "__main__":
  47.     config = get_saved_config()
  48.     set_modes(config
RAW Paste Data Copied