Python and getting PIDs???

Discussion in 'Mac Programming' started by myjay610, Jan 7, 2009.

  1. myjay610 macrumors regular

    Jan 6, 2008
    Hi all,
    Tough question, searched the web for hours and everything. The python function Popen from the subprocess module can be used to launch processes, easy enough. I want to use this to launch URLs in Safari and obtain the PID of the Safari process. Normal circumstances would allow this but since you have to use the open() call to launch the URL actually returns the pid of the open() process (or some sub-process launched by it, either way it isn't Safari's)
    >>> p = Popen(["open","-n",""])

    now (from the MacOS directory of the Safari bundle) if I did:
    p = Popen(["./Safari"]) and printed it gives me the pid b/c I'm launching the process directly.

    Anyone ever messed around with this? Is there another way of launching Safari right into a URL without using the open() call? Lastly, is the open() call open source maybe? Could it be modified to return a child pid or something?

  2. hhas macrumors regular

    Oct 15, 2007
    Why do you want Safari's PID for?

    The usual way is to launch Safari via LaunchServices/Process Manager/whatever if it isn't already running, then send it a 'get URL' (GURL/GURL) Apple event, passing a URL string as the direct parameter. e.g. Using Python appscript:

    from appscript import *
  3. myjay610 thread starter macrumors regular

    Jan 6, 2008
    I need the PID because it's the only identifiable part of a crash report that lets you know which instance of Safari crashed. So if I can record URLs and PIDs I can tell which URL causes Safari to crash, only if crash report told you which URL crashed!
  4. hhas macrumors regular

    Oct 15, 2007
    Fair enough.

    Appscript targets applications by Unix PID for the most part, so if you know where to fish (the APIs are undocumented, but now stable) you can extract the relevant information:

    from struct import unpack
    from appscript import *
    # identify Safari by name/path/bundle id, and appscript will target it by PID
    safari = app(id='')
    # next line ensures Safari is running and gets its PID
    pid = unpack('i',[0]
    print pid
  5. myjay610 thread starter macrumors regular

    Jan 6, 2008
    Ah, thanks! I never toyed with appscript but it seems pretty cool!

Share This Page