Sai Karthik

Balancing the braces ...

Sway Monitor Swapping Script

May 16, 2024 | 1 minute read
  • This is a simple python script i wrote & use swap between monitors in sway window manager.

  • Although, there is a more advanced tool named kanshi where the user can setup profiles to switch between & supports hotswapping of monitors when plugged in/out, My use case is simple. So, i wrote my own.

  • This script takes advantage of the swaymsg command’s json output feature. This command is used to configure sway while it’s running.

  • When invoked, This script checks if more than one monitor is attached & switches the output to the monitor with defined name.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python3
import subprocess as s
import json


def swap():
    r = s.run(["swaymsg", "-t", "get_outputs", "-r"], capture_output=True)

    monitors = json.loads(r.stdout)

    if len(monitors) > 1:
        for i in monitors:
            if i["name"] == "HDMI-A-1":
                s.run(["swaymsg", "output", i["name"], "enable"])
                s.run(["swaymsg", "output", "LVDS-1", "disable"])
                return

    # enable native monitor if no ext monitor is attached
    else:
        s.run(["swaymsg", "output", monitors[0]["name"], "enable"])

swap()
Comment | Share

Tags: sway linux