Python and getting PIDs???

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

  1. myjay610 macrumors regular

    Joined:
    Jan 6, 2008
    #1
    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 Popen.pid actually returns the pid of the open() process (or some sub-process launched by it, either way it isn't Safari's)
    example:
    >>> p = Popen(["open","-n","http://www.apple.com"])
    >>> p.pid
    63272

    now (from the MacOS directory of the Safari bundle) if I did:
    p = Popen(["./Safari"]) and printed p.pid 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?

    Thanks!
    John
     
  2. hhas macrumors regular

    Joined:
    Oct 15, 2007
    #2
    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:

    Code:
    from appscript import *
    
    app('Safari').open_location('http://www.apple.com')
    
     
  3. myjay610 thread starter macrumors regular

    Joined:
    Jan 6, 2008
    #3
    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

    Joined:
    Oct 15, 2007
    #4
    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:

    Code:
    #!/usr/bin/python
    
    from struct import unpack
    from appscript import *
    
    # identify Safari by name/path/bundle id, and appscript will target it by PID
    safari = app(id='com.apple.safari')
    
    # next line ensures Safari is running and gets its PID
    pid = unpack('i', safari.AS_appdata.target().addressdesc.data)[0]
    
    safari.open_location('http://www.apple.com')
    
    print pid
     
  5. myjay610 thread starter macrumors regular

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

Share This Page