terminalcommand.py 1.51 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
"""terminalcommand.py -- A minimal interface to Terminal.app.

To run a shell command in a new Terminal.app window:

    import terminalcommand
    terminalcommand.run("ls -l")

No result is returned; it is purely meant as a quick way to run a script
with a decent input/output window.
"""

#
# This module is a fairly straightforward translation of Jack Jansen's
# Mac/OSX/PythonLauncher/doscript.m.
#

17
from warnings import warnpy3k
Benjamin Peterson's avatar
Benjamin Peterson committed
18
warnpy3k("In 3.x, the terminalcommand module is removed.", stacklevel=2)
19

20 21 22 23 24 25 26 27 28 29 30 31 32
import time
import os
from Carbon import AE
from Carbon.AppleEvents import *


TERMINAL_SIG = "trmx"
START_TERMINAL = "/usr/bin/open /Applications/Utilities/Terminal.app"
SEND_MODE = kAENoReply  # kAEWaitReply hangs when run from Terminal.app itself


def run(command):
    """Run a shell command in a new Terminal.app window."""
33
    termAddress = AE.AECreateDesc(typeApplicationBundleID, "com.apple.Terminal")
34 35 36 37
    theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
                                     kAutoGenerateReturnID, kAnyTransactionID)
    commandDesc = AE.AECreateDesc(typeChar, command)
    theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
38 39

    try:
40
        theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
41 42 43 44 45
    except AE.Error, why:
        if why[0] != -600:  # Terminal.app not yet running
            raise
        os.system(START_TERMINAL)
        time.sleep(1)
46
        theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
47 48 49 50


if __name__ == "__main__":
    run("ls -l")