20

In Mac 10.6, I want to cause an active application to become de-active, or minimized by Python

I know I could use sendKey in Windows with Python, then what about in Mac?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Yinan
  • 2,516
  • 4
  • 22
  • 23

5 Answers5

34

Here is what I found from a different question on Stack Overflow. It works pretty good for my problem.

import os
cmd = """
osascript -e 'tell application "System Events" to keystroke "m" using {command down}' 
"""
# minimize active window
os.system(cmd)
AstroCB
  • 12,337
  • 20
  • 57
  • 73
Yinan
  • 2,516
  • 4
  • 22
  • 23
  • 1
    I was looking for how to do this in Ruby and the same idea can be used as well... `puts \`osascript -e 'tell application "System Events" to keystroke "m" using {command down}'\`` or pass in a file to do additional osascripting `puts \`osascript example.as\`` – danmayer Jan 04 '12 at 04:16
8

Try appscript, an Apple event bridge available in PyPI:

from appscript import app, k
app('System Events').keystroke('N', using=k.command_down)
Alan Christopher Thomas
  • 4,532
  • 2
  • 23
  • 23
  • 2
    Please note that appscript is no longer developed or supported, and its use is not recommended for new projects. – tester Dec 03 '13 at 06:48
6

In addition to Yinan, which will send the keystroke to the currently active application, you can send it to a specific application as follows. Pass the following to osascript as before, or save it to a file and pass the file to osascript

tell application "Safari"
    activate
    tell application "System Events" to keystroke "r" using {command down}
end tell

This will send Cmd + r to Safari after bringing it to the foreground

Svenito
  • 510
  • 4
  • 6
0

Maybe you could run an OSA script (man osascript) from Python, for instance, and drive the application?

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260
0

To make my scripts which already work on Windows using SendKeys from pip also work on OS X, I made a file /Library/Python/2.7/site-packages/SendKeys/__init__.py (site-packages is where pip puts everything it installs on my Mac... not sure if that's configurable or not.)

The contents of the file are:

def SendKeys(keys):
    if keys == '{ENTER}'
        keys = 'return'
    from os import system
    system('osascript -e \'tell application "System Events" to keystroke ' + keys + "'")

Obviously it's not very robust, so I won't be putting it on pypi, but it's enough to make my scripts run on both OS X and Windows.

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193