Ubuntu – Script / Shortcut to switch display priority

command linedisplaymultiple-monitorsshortcut-keysxrandr

I wish to have a shortcut which switches the priority (i.e. primary, secondary) of the displays (laptop + external).

PS: I am aware that there's a dedicated button/shortcut to do this but, at least mine, cycles through all configurations (i.e. different resolutions). I want to cycle between two configurations only.

Best Answer

It turned out I already wrote it, as part of this question. Since it is another question, below an outtake of that one:

#!/usr/bin/env python3
import subprocess

# Look up the currently set primary screen, set it to the other one
scr_data = subprocess.check_output(["xrandr"]).decode("utf-8").splitlines()
scrs = [[l.split()[0], "primary" in l] for l in scr_data if " connected" in l]
for screen in scrs:
    if not screen[1]:
        subprocess.Popen(["xrandr", "--output", screen[0], "--primary"])

It toggles (switches between the two) the primary screen.

To use:

  • copy the script into an empty file, save it as toggle_primary.py

  • Add it to a shortcut key: choose: System Settings > "Keyboard" > "Shortcuts" > "Custom Shortcuts". Click the "+" and add the command:

      python3 /path/to/toggle_primary.py
Related Question