| 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 | import time
|
|---|
| 18 | import os
|
|---|
| 19 | from Carbon import AE
|
|---|
| 20 | from Carbon.AppleEvents import *
|
|---|
| 21 |
|
|---|
| 22 |
|
|---|
| 23 | TERMINAL_SIG = "trmx"
|
|---|
| 24 | START_TERMINAL = "/usr/bin/open /Applications/Utilities/Terminal.app"
|
|---|
| 25 | SEND_MODE = kAENoReply # kAEWaitReply hangs when run from Terminal.app itself
|
|---|
| 26 |
|
|---|
| 27 |
|
|---|
| 28 | def run(command):
|
|---|
| 29 | """Run a shell command in a new Terminal.app window."""
|
|---|
| 30 | termAddress = AE.AECreateDesc(typeApplSignature, TERMINAL_SIG)
|
|---|
| 31 | theEvent = AE.AECreateAppleEvent(kAECoreSuite, kAEDoScript, termAddress,
|
|---|
| 32 | kAutoGenerateReturnID, kAnyTransactionID)
|
|---|
| 33 | commandDesc = AE.AECreateDesc(typeChar, command)
|
|---|
| 34 | theEvent.AEPutParamDesc(kAECommandClass, commandDesc)
|
|---|
| 35 |
|
|---|
| 36 | try:
|
|---|
| 37 | theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
|
|---|
| 38 | except AE.Error, why:
|
|---|
| 39 | if why[0] != -600: # Terminal.app not yet running
|
|---|
| 40 | raise
|
|---|
| 41 | os.system(START_TERMINAL)
|
|---|
| 42 | time.sleep(1)
|
|---|
| 43 | theEvent.AESend(SEND_MODE, kAENormalPriority, kAEDefaultTimeout)
|
|---|
| 44 |
|
|---|
| 45 |
|
|---|
| 46 | if __name__ == "__main__":
|
|---|
| 47 | run("ls -l")
|
|---|