views:

76

answers:

2

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. Thanks, everyone!

+3  A: 

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.

delnan
Hmm... sys.modules is a dict, with some keys that start with "idlelib.", so I could check for that. But it sounds like a hack, so I'd like to avoid it. They can even have different lengths (2.6.5:149, 2.7:152).
KeJi
Well, I guess this isn't possible without ugly hacks. That's the reason I ask why you think you need to...
delnan
With the console, I want to be able to clear the screen, move the cursor, add color, use msvcrt.getch, etc. Most of those don't seem to work in IDLE, and some will even fail silently, so instead of letting that happen, I'd rather make it check if it's running in IDLE or not.
KeJi
Well, I fear you're out of luck here. Unless you want to hack around, that is. Sorry.
delnan
+1  A: 

My suggestion is to get list of all running frames and check if main Idle method would be in there.

def frames(frame = sys._getframe()):
    _frame = frame
    while _frame :
        yield _frame
        _frame = _frame.f_back
import idlelib.PyShell
print(idlelib.PyShell.main.func_code in [frame.f_code for frame in frames()])

the frames function generates frames running at moment of its declaration, so you can check if idle were here.

Odomontois
It works, but if it wasn't opened with a script, then it returns False. But there are other idlelib objects in it like <code object runcode at 00B9AE30, file "C:\Python26\lib\idlelib\run.py", line 287>. (tried with 2.6)
KeJi