| 1 | """terminalcommand.py -- A minimal interface to Terminal.app.
|
|---|
| 2 |
|
|---|
| 3 | To run a shell command in a new Terminal.app window:
|
|---|
| 4 |
|
|---|
| 5 | import terminalcommand
|
|---|
| 6 | terminalcommand.run("ls -l")
|
|---|
| 7 |
|
|---|
| 8 | No result is returned; it is purely meant as a quick way to run a script
|
|---|
| 9 | with a decent input/output window.
|
|---|
| 10 | """
|
|---|
| 11 |
|
|---|
| 12 | #
|
|---|
| 13 | # This module is a fairly straightforward translation of Jack Jansen's
|
|---|
| 14 | # Mac/OSX/PythonLauncher/doscript.m.
|
|---|
| 15 | #
|
|---|
| 16 |
|
|---|
| 17 | from warnings import warnpy3k
|
|---|
| 18 | warnpy3k("In 3.x, the terminalcommand module is removed.", stacklevel=2)
|
|---|
| 19 |
|
|---|
| 20 | import time
|
|---|
| 21 | import os
|
|---|
| 22 | from Carbon import AE
|
|---|
| 23 | from Carbon.AppleEvents import *
|
|---|
| 24 |
|
|---|
| 25 |
|
|---|
| 26 | TERMINAL_SIG = "trmx"
|
|---|
| 27 | START_TERMINAL = "/usr/bin/open /Applications/Utilities/Terminal.app"
|
|---|
| 28 | SEND_MODE = kAENoReply # kAEWaitReply hangs when run from Terminal.app itself
|
|---|
| 29 |
|
|---|
| 30 |
|
|---|
| 31 | def run(command):
|
|---|
| 32 | """Run a shell command in a new Terminal.app window."""
|
|---|
| 33 | termAddress = AE.AECreateDesc(typeApplicationBundleID, "com.apple.Terminal")
|
|---|
| 34 | theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
|
|---|
| 35 | kAutoGenerateReturnID, kAnyTransactionID)
|
|---|
| 36 | commandDesc = AE.AECreateDesc(typeChar, command)
|
|---|
| 37 | theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
|
|---|
| 38 |
|
|---|
| 39 | try:
|
|---|
| 40 | theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
|
|---|
| 41 | except AE.Error, why:
|
|---|
| 42 | if why[0] != -600: # Terminal.app not yet running
|
|---|
| 43 | raise
|
|---|
| 44 | os.system(START_TERMINAL)
|
|---|
| 45 | time.sleep(1)
|
|---|
| 46 | theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
|
|---|
| 47 |
|
|---|
| 48 |
|
|---|
| 49 | if __name__ == "__main__":
|
|---|
| 50 | run("ls -l")
|
|---|