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)