How to know which application run a python script
Question: Is there a way to know which application I'm running a python script from?

I can run python from multiple sources, like Textmate, Sublime Text 2 or
Terminal (I'm on Mac OSX). How can I know, exactly which tool launched the
current python app.

I've tried looking into the `os` and `inspect` modules, but couldn't find the
solution.


Answer: You can use [psutil](http://code.google.com/p/psutil/) to do this sort of
thing in a fairly cross-platform way:

    
    
    import psutil
    my_process = psutil.Process(os.getpid())
    parent = my_process.parent
    print "Parent process name: " + parent.name
    

From the `psutil` documentation:

> It currently supports Linux, Windows, OSX and FreeBSD, both 32-bit and
> 64-bit, with Python versions from 2.4 to 3.3 by using a single code base.

As well as the name you can get the executable path (which might be more
useful if you're selecting from a list of options) and also the full command-
line with which it was invoked. You can also get the username who ran the
process. See the [psutil classes
documentation](http://code.google.com/p/psutil/wiki/Documentation#Classes) for
details of the parameters and the platforms on which they're available.

As an aside, if at all possible I would structure your code so that you
_don't_ have to modify your behaviour according to the calling application -
it would be much preferable to have the calling application pass in a
parameter which modifies the behaviour of the shared code. However, I
appreciate that sometimes other concerns take precedence over cleanliness of
code, so `psutil` should enable you to do what you requested.

