What code can I use to check if script is running in IDLE?

Just as the title says. I want to write a script that behaves differently depending on whether it's running inside a console window or in IDLE. Is there an object that exists only when running in IDLE that I can check for? An environment variable?

I'm using Python 2.6.5 and 2.7 on Windows.

Edit:

The answers given so far work. But I'm looking for an official way to do this, or one that doesn't look like a hack. If someone comes up with one, I'll accept that as the answer. Otherwise, in a few days, I'll accept the earliest answer.


I would prefer to do:

import sys
print('Running IDLE' if 'idlelib.run' in sys.modules else 'Out of IDLE')

Google found me this forum post from 2003. With Python 3.1 (for win32) and the version of IDLE it comes with, len(sys.modules) os 47 in the command line but 122 in the IDLE shell.

But why do you need to care anyway? Tkinter code has some annoyances when run with IDLE (since the latter uses tkinter itself), but otherwise I think I'm safe to assume you shouldn't have to care.


I suggest packing all the code in one function (Python 3):

def RunningIntoPythonIDLE():

    import idlelib.PyShell

    def frames(frame = sys._getframe()):
        _frame = frame
        while _frame :
            yield _frame
            _frame = _frame.f_back

    return idlelib.PyShell.main.__code__ in [frame.f_code for frame in frames()]

So tkinter apps can do its check:

if not RunningIntoPythonIDLE():
    root.mainloop()

I'm a touch late, but since IDLE replaces the standard streams with custom objects (and that is documented), those can be checked to determine whether a script is running in IDLE:

import sys

def in_idle():
    try:
        return sys.stdin.__module__.startswith('idlelib')
    except AttributeError:
        return True