0

I'm making an app (in python) that requires a way to switch macOS virtual desktops (spaces) using a keyboard shortcut, terminal command, etc. It pretty much doesn't matter how its done as long as it doesn't interfere with using the computer and can be triggered using python.

Currently I have tried using the pynput and keyboard python libraries to press ctrl+left/right arrow, but that doesn't work (Accessibility permission is enabled). Instead of switching to the space left or right it just shows things like ^[[1;5C1 in the terminal, or having no apparent effect when any other apps are in focus. Changing the keyboard shortcut to switch spaces from ctrl+left/right to shift+left/right doesn't seem to help.

Is there any way to do this?

0

1 Answer 1

0

Using ctrl-left and ctrl-right to switch desktops is brittle, because you're dependent on the user having that in their keyboard mappings.

Having said that, this Applescript fragment will shift desktops left or right, depending.

tell application "System Events"
    -- key code 123 is left arrow
    -- key code 124 is right arrow
    key code 123 using {control down}
end tell

If you want to execute this from python, a good reference is Dr Drang's posting at leancrew. I reproduce the important bits here in case the posting goes away. The posting is old enough that it's python2, I fixed it up for python3.

First the module, applescript.py

# dr drang appleScript handler for python
# http://www.leancrew.com/all-this/2013/03/combining-python-and-applescript/

import subprocess

def asrun(ascript):
  "Run the given AppleScript and return the standard output and error."

  osa = subprocess.Popen(['osascript', '-'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE)
  return osa.communicate(bytes(ascript,'UTF-8'))[0]

def asquote(astr):
  "Return the AppleScript equivalent of the given string."

  astr = astr.replace('"', '" & quote & "')
  return '"{}"'.format(astr)

Here's an example, all in one file vs importing the module. This will move one desktop left.

# dr drang appleScript handler for python
# http://www.leancrew.com/all-this/2013/03/combining-python-and-applescript/

import subprocess

def asrun(ascript):
  "Run the given AppleScript and return the standard output and error."

  osa = subprocess.Popen(['osascript', '-'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE)
  return osa.communicate(bytes(ascript,'UTF-8'))[0]

def asquote(astr):
  "Return the AppleScript equivalent of the given string."

  astr = astr.replace('"', '" & quote & "')
  return '"{}"'.format(astr)


ascript = '''
tell application "System Events"
    -- key code 123 is left arrow
    -- key code 124 is right arrow
    key code 123 using {control down}
end tell
'''

asrun(ascript)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .