views:

437

answers:

2

I know the process id of an application in Mac OS X. How can I switch to it (using applescript, or python, or whatever)?

By "switch", I mean, put in focus.

The usual solution is to use the applescript code tell application "Foo" activate, but here the name is not useful because I have many instances of the same application running. I am however able to get the process id of the application.

How can I switch to this application programmatically?

+1  A: 

Here is my solution, with python and applescript:

  1. Install appscript
  2. Run appscript.app(pid=<yourpid>).activate()

That's it!

Olivier
+2  A: 

If you don't want to /can't install any additional software, there is a built-in way of looking up process IDs and apps: ps.

ps is a useful command line tool to find info on running processes. To find a particular app given the process number (which I've assigned to a variable myProcessId):

do shell script "ps -p " & myProcessId

this will return a result like this

  PID TTY           TIME CMD
66766 ??         9:17.66 /Applications/Firefox.app/Contents/MacOS/firefox-bin -psn_0_3793822

to restrict the result to just the relevant line, pipe it to grep like so

do shell script "ps -p " & myProcessId & "|grep " & myProcessId

By parsing the answer you can find the name of the app. This might be a little tricky because the result will show the actual command used for the app, not the app name (if you look at the example you'll see it is possible to find it by looking for something.app in the result).

Edit - sorry, I misunderstood the question.

You can do it with system events (turns out to be much easier than faffing around with the shell anyway):

tell application "System Events"
    set theprocs to every process whose unix id is myProcessId
    repeat with proc in theprocs
        set the frontmost of proc to true
    end repeat
end tell
stib
I know that, but it is not interesting for me. As I already explained in my question, I already know the name of the app, but there are several of them. The only way I can differentiate between them is by the process ID, which I happen to know.
Olivier
oh, I see. See the edit above.
stib